-2

I have this very simple code. I am trying to figure out how I can simultaneously alter the object reference in the array with the object reference that was first placed into the array. I want to know how to bind the two references/values.

In JavaScript, which is very similar to Java in terms of passing by value, the best we probably can do is to use Object.observe() like so: http://www.html5rocks.com/en/tutorials/es7/observe/

but with Java, I wonder if there is a good way to do this without writing your own library?

 public class ArrayRefVal {

    public static void main(String[] args) {
        ArrayList<Object> al = new ArrayList<Object>();
        Object s = new Object();
        al.add(s);
        s = null;
        System.out.println(al.get(0));
    }
}

likewise:

public class ArrayRefVal {

    public static void main(String[] args) {
        ArrayList<Object> al = new ArrayList<Object>();
        Object s = new Object();
        al.add(s);
        al.set(0, null);
        System.out.println(s);
    }
}

turns out JavaScript has the same behavior as Java on this one. How can I somehow bind the element in the array with the object s, such that when I change the element in the array it changes the original object?

Did I mention this already? I want to know how to bind the two references/values.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

1

You cannot do it in the way you like, because you cannot change the existing String in Java, neither can you update local variable s in non-explicit way (without using assignment operator like = or +=). If you want such indirection, you can introduce some intermediate reference object:

public class ArrayRefVal {
    static class Ref<T> {
        T obj;

        public Ref(T obj) {
            this.obj = obj;
        }

        @Override
        public String toString() {
            return String.valueOf(obj);
        }
    }

    public static void main(String[] args) {        
        ArrayList<Ref<String>> al = new ArrayList<>();
        Ref<String> s = new Ref<>("hiii");
        al.add(s);
        al.get(0).obj = "barg"; 
        System.out.println(s); //prints "barg"
    }
}

However you should care to use the Ref at every place where it's necessary.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • 1
    Why write your own `Ref` class when [java has one](http://docs.oracle.com/javase/7/docs/api/java/lang/ref/Reference.html) already. – Codebender Jul 15 '15 at 05:51
  • 1
    @Codebender, this one badly suits the OP needs. It's abstract, so you would need to subclass it anyways. Its interface does not allow to update the referenced value. The `AtomicReference` class suits much better and must be used in concurrent environment, but it will produce unnecessary overhead in single-threaded case. – Tagir Valeev Jul 15 '15 at 05:54