2017-03-19 65 views
-2

引用的項目我只是想知道如果Java提供任何會允許:更新並以列表

<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) 

從我可以告訴,這不符合任何Java的名單的工作。實質上,我在問是否有一個集合類型會根據其外部引用更新其內部元素。在上面的例子中,我想它所以設置「F」到富的新實例也將在列表條目中反映出來。這也意味着以下將是真實的:

<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" 

這樣的事情是否存在?

編輯:

爲了澄清,原來的對象添加到需要爲空列表。然後更新該對象,並且該更新應該反映在列表中。在上面的實例中,富變量是在第一,和被添加到列表中時,它仍然是空。添加後,我將其設置爲Foo的新實例。我想知道是否有一個列表類型,當我實例化Foo時,也更新列表。

+0

的[對象添加到一個ArrayList和修改它以後(HTTP可能重複://計算器.COM /問題/ 7080546 /加載的對象到一個-的ArrayList和 - 修改 - 它更高版本) – nullpointer

+0

爲什麼要補充'null'到列表中,然後修改'F'?當你這樣做時,你不會修改列表中的空條目。 'F'是一個參考,而_reference_的副本存儲在列表中,而不是參考參考。如果您需要2級間接尋址,則必須將引用包裝到類中,並將該類的實例存儲在列表中。 –

回答

0

回答你的問題有關含有看看下面這個例子

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

它打印出真實的,爲什麼呢?因爲String類重寫等於和哈希方法(從Object類,所有類從對象擴展)

如果你沒有得到等於那是因爲你需要探測的方法等於傳遞時,它會得到實現。

0

最簡單的方式來實現你所尋找的是包裝在另一大類您參考:

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());