2017-01-27 59 views
0

所以我創建了三個名爲「地址」,「工作」和「人」的類,其中「人」是我的主類。我測試這些:創建一個存儲在ArrayList中創建的所有對象的類?

Address person2Address = new Address(1054, "Pico St", "Los Angeles", "CA", "97556"); 
    Address person2JobAddress = new Address(5435, "James St", "New York", "NY", "56565"); 
    ArrayList<String> person2Phone = new ArrayList<String>(); 
    person2Phone.add("555-555-55"); 
    Job person2Job = new Job("Mechanic", 35000.00, person2JobAddress); 
    Person person2 = new Person("Rollan Tico", "New York", 'M', person2Address, person2Job, person2Phone); 
    System.out.println(person2.toString()); 

他們打印正確的一切。現在,這是我卡住的地方。我將如何創建一個名爲Persons的不同類來存儲在ArrayList中創建的每個Person?會不會有任何問題?我知道一個Arrayist是由ArrayList<Person> List = new ArrayList<Person>();創建的,但有一種感覺我錯過了一些東西。

+0

你不需要一個單獨的類。假設你正在尋找一個不可變的列表,你可以使用'List persons = Arrays.asList(person1,person2,...);' –

+0

@JacobG。 'Arrays.asList()'不是不可變的,只是固定大小。 – shmosel

回答

1

您可以收集喜歡

Collection<Person> persons = new ArrayList<Person>(); persons.add(person2);

或在某些情況下,如JSON序列化,你不能seralize列表作爲根元素。所以,

import java.util.* 

public class Persons { 

    private Collection<Person> persons; 

    //If you want the clients to have flexibility to choose the implementation of persons collection. 
    //Else, hide this constructor and create the persons collection in this class only. 
    public Persons(Collection<Person> persons) { 
    this.persons = persons; 
    } 

    public void addPerson(Person person) { 
    persons.add(person); 
    } 
} 
+0

我不能直接傳遞數組列表:/?請你詳細說明爲什麼你使用收藏品,如果你可以用Arraylist做@larivis – minigeek

+0

是的,你可以。 'List personList = new ArrayList (); personList.add(person1); //等等...... 人員=新人員(personList);' 如果您擁有一個Collection 字段,您就不需要這個新類。 – harivis

+0

ohk thanx :)所以我不需要鍵入.add每次添加新的人,如果我使用collectionlist,對不對? @harivis +1 – minigeek

0

如果你像Person對象創建一個類,你不只是需要創建一個Persons類存儲多個Person對象。除非您必須定義涉及多個對象的操作,例如類別爲Group類,其中包含對組pf人員執行的操作,在這種情況下創建PersonsGroup類是有意義的。在你的情況下,我會假設你只需要存儲多個Person對象,因爲ArrayList<Person>就足夠了。

ArrayList<Person> persons = new ArrayList<Person>(); 
persons.add(new Person(.....)); //add Person 
. 
. 
Person person1=persons.get(1); //get Person by index 
相關問題