2012-11-26 3 views
-1

다른 클래스의 객체를 포함하는 arraylist를 이해하는 데 문제가 있습니다. 나는 6 개의 물건을 가지고있다. 모든 개체는 공통적으로 2 개의 특성을가집니다. (ID, Type) 모든 개체에는 고유 한 특성이 있습니다. 2 atr (ID, Type)의 mainObject 클래스를 만들었습니다. 다른 객체는 mainObject를 확장하여 가지고 있기 때문에다른 객체 클래스의 Java arraylist

class mainClass{ 
    this.id=id; 
    this.type=type; 
} 
class extendedClass extends mainClass{ 
    super(ID,Type); 
    this.atr1=atr1; 
} 

class extendedClass2 extends mainClass{ 
    super(ID,type); 
    this.atr2=atr2; 
    this.atr3=atr3; 
} 

나는 파일에서 정보를 읽었다.

FileInputStream fstream = new FileInputStream("data.txt"); 
// Get the object of DataInputStream 
DataInputStream in = new DataInputStream(fstream); 
BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
String strLine; 
// Read File Line By Line 
while ((strLine = br.readLine()) != null) { 
    // Print the content on the console 
    String s[] = strLine.split("\\|"); 
    mainClass myObj = new mainClass(s[0], s[1]); 

ArrayList<mainClass> items = new ArrayList<mainClass>(); 
items.add(myObj); 

나는 모든 개체 라인으로 파일 라인에서 읽혀질해야하고 배열 목록에 저장합니다. 어떻게해야합니까? ArrayList<Object> list = new ArrayList<Object>을 시도했지만 작동하지 않습니다. 요점은 파일에서 모든 객체를 읽고 선택한 속성 (ID, 유형)으로 정렬합니다.

+0

'ArrayList '로 시작하십시오. –

+0

코드에 어떤 문제가 있습니까? 그것이 작동 할 것 같은데. – Kai

+0

@ Serv0 : 샘플 클래스가 실제로 컴파일되지 않는다면, 코드는 생성자 안에 넣어 져야합니다. ... –

답변

3

당신은 당신이 mainClass의 목록을 필요가 올바른지 : 당신이하지 그 안에, while 루프 전에이 줄을 추가해야하지만

ArrayList<mainClass> items = new ArrayList<mainClass>(); 

.

ArrayList<mainClass> items = new ArrayList<mainClass>(); 

while ((strLine = br.readLine()) != null) { 
    // etc... 
    items.add(myObj); 
}