-2

I was just wondering if Java provides anything that would allow the following:

<Some List> list = new <Some List>;
Foo f = null;
list.add(f);
f = new Foo();

//Where this would be true
list.contains(f)

//As well as this (which is kind of implied by the contains call)
f == list.get(0)

From what I can tell, this does not work with any of Java's lists. In essence, I am asking if there is a collection type that will update their inner elements in accordance with their external references. In the example above, I would like it so setting 'f' to the new instance of Foo would also be reflected in the list entry. This would also imply the following would be true:

<Some List> list = new <Some List>;
Foo f = null;
list.add(f);
f = new Foo();
f.name = "banana";

//Where this would be true and not cause an NPE, as it does with List
f.name == list.get(0).name //Both would equal "banana"

Does anything like this exist?

Edit:

To clarify, the original object added to the list needs to be null. That object is then updated, and that update should be reflected in the list. In the examples above, the Foo variable is null at first, and is added to the list when it is still null. After adding it, I then set it to a new instance of Foo. I am wondering if there is a list type that, when I instantiate Foo, also updates the list.

thearchitector
  • 187
  • 3
  • 12
  • Possible duplicate of [Add an object to an ArrayList and modify it later](http://stackoverflow.com/questions/7080546/add-an-object-to-an-arraylist-and-modify-it-later) – Naman Mar 19 '17 at 05:21
  • Why are you adding `null` to the list and then modifying `f`? When you do so you are not modifying the null entry in the list. `f` is a reference, and a copy of the _reference_ is stored in the list, not a reference to the reference. If you need 2-level indirection you must wrap the reference in a class and store instances of the class in the list. – Jim Garrison Mar 19 '17 at 06:08

2 Answers2

0

Answering your question about contains look at this example

        List<String> test = new ArrayList<String>();
        String one = new String("one");
        test.add(one);
        one = new String("one");
        System.out.println(test.contains(one));

It prints true, why? because String class override equals and hash methods (From Object class, all Class extends from Object)

If you don't get equals it is because you need to probe that the method equals will get true when you pass it.

Yussef
  • 610
  • 6
  • 11
0

The simplest way to achieve what you are looking for is to wrap your reference in another class:

class FooRef {
    private Foo foo = null;

    public void setFoo(Foo foo) {
        this.foo = foo;
    }

    public Foo getFoo() {
        return foo;
    }
}

List<FooRef> fooRefs = new ArrayList<>();
FooRef ref = new FooRef(foo1);
fooRefs.add(ref);
ref.setFoo(foo2);
assertSame(foo2, fooRefs.get(0).getFoo());
sprinter
  • 27,148
  • 6
  • 47
  • 78