【发布时间】:2012-11-26 12:30:11
【问题描述】:
我在理解包含来自不同类的对象的数组列表时遇到了问题。我有 6 个对象。所有对象都有 2 个共同的属性。(ID,类型) 每个对象都有自己的属性。我用 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>,但它不起作用。重点是从文件中读取所有对象,根据选择的属性(id,type)对它们进行排序。
【问题讨论】:
-
以
ArrayList<MainClass>开头。 -
你的代码有什么问题。看起来它可以工作。
-
@Serv0:您的示例类并没有真正编译,代码必须放在构造函数中......
-
您需要确保大括号在正确的位置并正确缩进。不清楚 while 循环在哪里结束。
-
@JanDvorak 我可以这样做:[code]while ((strLine = br.readLine()) != null) { String s[] = strLine.split("\\|"); ItemObject myObj = new ItemObject(s[0], s[1]); ArrayList
items = new ArrayList (); items.add(myObj); for(ItemObject temp : items){ System.out.println("id :"+temp.getID()+"Type :"+temp.getObjectType()); } }'[code] 但只有 mainClass 属性将存储在列表中,我如何访问其他属性。如果 arraylist 类型是 mainClass,则无权访问其他类函数 f.e。获取Atr3()? temp.getClass.???
标签: java class object arraylist