![](/img/trans.png)
[英]Java - Are ArrayList and ArrayList<Object> two different classes?
[英]Java arraylist of different object class
我对理解包含不同类对象的arraylist有一个问题。 我有6个物件。 所有对象都有2个共同的属性。(ID,Type)每个对象都有自己的属性。 我创建了具有2 atr(ID,Type)的mainObject类。 其他对象扩展了mainObject,因此它们具有
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>
,但是它不起作用。 重点是从文件中读取所有对象,并根据选择的attribute(id,type)对它们进行排序。
您是正确的,您需要一个mainClass
列表:
ArrayList<mainClass> items = new ArrayList<mainClass>();
但是,您应该将此行放在while循环之前,而不是在其中。
ArrayList<mainClass> items = new ArrayList<mainClass>();
while ((strLine = br.readLine()) != null) {
// etc...
items.add(myObj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.