2014-09-02 33 views
-1

我有對象的集合,A如何建立一套深對象

class A{ 
    String name; 
    Collection<B> listOfB; 
} 

class B { 
    String address; 
    String phone; 
    int age; 
} 

我想創建一個對象,其中兩個對象具有相同的名稱,地址和電話的新的集合。任何人都可以告訴我這是否是最好的方法?

我創建了Key-A的映射。關鍵將如下:

Key { 
String name; 
String address; 
String phone; 
} 

我只作爲一個對象的列表,如果他們相應的密鑰不存在。

+3

你的問題非常混亂。你能改說嗎? – 2014-09-02 09:33:51

回答

1

如果我正確理解你的問題,你想要一張地圖Map<Key, A>。重要的是,你定義了Key平等和哈希碼(如果你想有一個哈希地圖):

class Key { 
    String name; 
    String address; 
    String phone; 

    @Override // override in Object 
    public boolean equals(Object other) { 
     if(!other instanceof Key) return false; 
     Key otherKey = (Key) other; 
     return name.equals(otherKey.name) && address.equals(otherKey.address) && phone.equals(otherKey.phone); // check for null if fields can be null 
    } 

    @Override // override in Object 
    public int hashCode() { 
     return name.hashCode()^address.hashCode()^phone.hashCode(); // or something along those lines 
    } 
} 

而且好主意,以創建Key構造,使領域privatefinal

我不確定這個密鑰是如何派生出來的。理想的情況下,Key將以某種方式派生自0​​,或者 - 更好 - A將有hashCodeequals方法,因此您不需要地圖,但可以使用Set。這實際上取決於你想要建模的數據,而你的問題還不夠清楚,無法給出具體的建議。

-1

一是落實hascodeequals方法類B. 在equals方法的返回true時的姓名,電話和地址,都是一樣的。

第二次,創建地圖像這樣=

HashMap<B,A> myMap; 

地圖中的一個關鍵始終是唯一的。

+0

他想要一個專用的'Key'類。 – 2014-09-02 09:40:25

+0

不一定。我會採取任何良好的實施。 – TheCoder 2014-09-02 09:42:31

+0

@ heyya99:儘管如此,這個問題還不夠具體。真正重要的是如何爲任何'A'定義'Key'。 – 2014-09-02 09:46:28