2017-01-27 1 views
0

그래서 "Person"이 기본 클래스 인 "Address", "Job"및 "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를 직접 전달할 수 없습니까? /? uhrivis와 Arraylist가 함께 할 수 있다면 컬렉션을 사용하는 이유는 무엇인지 자세히 설명해 주시겠습니까 – minigeek

+0

예, 가능합니다. '목록 personList = 새 ArrayList (); personList.add (person1); //Persons persons = new Persons (personList); ' Collection 필드를 가지고 있으면이 새로운 클래스가 필요하지 않습니다. – harivis

+0

ohk thanx :) 그래서 collectionlist를 사용하면 매번 새로운 사람을 추가하기 위해 .add를 입력 할 필요가 없습니다. @ 하리브 +1 – minigeek

0

, 당신은 여러 Person 개체를 저장하는 단지 Persons 클래스를 만들 필요가 없습니다. 복수 Person 오브젝트를 포함하는 조작을 정의해야하는 경우 (예 : Group, 그룹 pf 담당자에 대해 조작이 수행되는 경우)는 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 
관련 문제