2017-01-27 5 views
0

"Address"、 "Job"、 "Person"という3つのクラスを作成し、 "Person"をプライマリクラスとしました。私はこれらを次のようにテストします: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()); 

すべてを正しく印刷します。さて、これは私が立ち往生している場所です。 ArrayListで作成された各Personを格納するPersonsという別のクラスを作成するにはどうすればよいですか?どんなconstrcunertがありますか?私はArrayistがArrayList<Person> List = new ArrayList<Person>();によって作成されていることを知っていますが、私は何かが足りないと感じています。

+0

別途クラスは必要ありません。あなたが不変のリストを探していると仮定すると、 'List persons = Arrays.asList(person1、person2、...);' –

+0

@JacobGを使うことができます。 'Arrays.asList()'は不変ではなく、固定サイズです。 – shmosel

答えて

1

あなたがルート要素としてリストをseralizeすることはできませんJSONのシリアライズよう

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

あるいはいくつかのケースでは、のようなコレクションを持つことができます。あなたはPersonのようなオブジェクトのクラスを作成した場合ので、

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を直接渡すことはできません:/?なぜあなたはArraylistでも@harivisと一緒にそれをやることができるなら、あなたがコレクションを使用した理由を詳述できますか? – minigeek

+0

はい、できます。 'リスト personList =新しいArrayList (); personList.add(person1); //Persons persons = new Persons(personList); ' Collection フィールドを持っていればこの新しいクラスは必要ありません。 – harivis

+0

ohk thanx :)だから、コレクションリストを使用すると、毎回.addを入力して新しい人を追加する必要はありません。 @ハリビス+1 – minigeek

0

、あなただけの複数のPersonオブジェクトを格納するためにPersonsクラスを作成する必要はありません。例えばGroupクラスのような複数のオブジェクトを含む操作を定義する必要がない場合は、PersonsまたはGroupクラスを作成すると意味があります。あなたの場合、私は複数のPersonオブジェクトを格納する必要があると仮定し、そのためArrayList<Person>で十分です。

ArrayList<Person> persons = new ArrayList<Person>(); 
persons.add(new Person(.....)); //add Person 
. 
. 
Person person1=persons.get(1); //get Person by index 
関連する問題