【问题标题】:Java arraylist of different object class不同对象类的Java数组列表
【发布时间】: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&lt;Object&gt; list = new ArrayList&lt;Object&gt;,但它不起作用。重点是从文件中读取所有对象,根据选择的属性(id,type)对它们进行排序。

【问题讨论】:

  • ArrayList&lt;MainClass&gt;开头。
  • 你的代码有什么问题。看起来它可以工作。
  • @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


【解决方案1】:

您是正确的,您需要mainClass 的列表:

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

但是你应该把这一行放在while循环之前,而不是里面。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2016-09-07
    • 2014-07-02
    • 2014-03-17
    • 1970-01-01
    相关资源
    最近更新 更多