[英]Object ArrayList within Object ArrayList extended by class java
我创建了一个包含一组对象的类,这些对象包含名为“ 附件 ”的字符串和布尔值
然后创建ArrayList类,然后将其添加到名为“ AccessoriesList ”的列表中,从那里输入更多数据。
然后,我使用for循环创建了一个附件对象,以从ArrayList接收数据。 这仍然为null。
我环顾四周,发现最常见的问题是变量尚未初始化。 所以我尝试并且仍然得到相同的结果
所以这是配件课
public static class Accessories {
Accessories(String Accessoriesname, boolean cold, boolean warm, boolean hot, boolean rain, boolean snow, boolean ice, boolean formal, boolean informal) {
}
String name =null ; boolean cold; boolean warm; boolean hot; boolean rain; boolean snow; boolean ice; boolean formal; boolean informal;
}
这是AccessoriesList类
public ArrayList createAccessories() {
ArrayList<Accessories> Accessoriesist = new ArrayList<Accessories>();
Accessoriesist.add(new Accessories("Bag", true, true, true, false, false, false, true, true));
Accessoriesist.add(new Accessories("Gloves", true, false, false, true, true, true, true, true));
Accessoriesist.add(new Accessories("Hat", true, false, false, true, true, true, false, true));
Accessoriesist.add(new Accessories("Poncho", false, true, true, false, false, false, false, true));
Accessoriesist.add(new Accessories("Scarf", true, true, false, true, true, true, true, true));
Accessoriesist.add(new Accessories("Sunglasses", false, true, true, false, false, false, true, true));
Accessoriesist.add(new Accessories("Tie", true, true, true, true, true, true, true, true));
Accessories getAccessories =null;
String getname = null;
for (int i = 0; i < Accessoriesist.size(); i++) {
getAccessories = Accessoriesist.get(i);
getname = getAccessories.name;
System.out.println("this is the name : " + getname);
System.out.println("this is the Accessoriesist : " + Accessoriesist.get(i));
}
return Accessoriesist;
}
我没有收到信息,而是收到哈希码。
我试图将一个ArrayList中的附件对象(原始)放入另一个附件对象(新)中。 我试图从附件对象(新)中提取数据
您有两个问题:
首先,构造函数永远不要将传递给它的属性复制到该类中:附件(字符串附件名称,布尔冷,布尔温暖,布尔热,布尔雨,布尔雪,布尔冰,布尔正式,布尔非正式){}
将构造函数视为带有可变参数的方法调用:在这种情况下,您在花括号{
和}
之间不执行任何操作。 Java为您提供了this
关键字来引用类实例的属性。 因此,您需要将传递给构造函数的参数显式复制到类实例的属性中:
Accessories(String Accessories name, boolean cold, boolean warm, boolean hot, boolean rain, boolean snow, boolean ice, boolean formal, boolean informal) {
this.name = name
this.cold = cold
this.warm = warm
this.hot = hot
this.rain = rain
this.snow = snow
this.ice = ice
this.formal = formal
this.informal = informal
}
其次,由于此行代码将一个String与一个对象串联在一起,因此它将在您的Accessories对象上调用.toString()方法:
System.out.println("this is the Accessoriesist : " + Accessoriesist.get(i));
.toString()
方法的默认实现是从Object超类继承的。 如果您想重写它,只需将一个方法添加到您的类中,该方法具有与Object.toString()
相同的方法签名
public String toString() {
StringBuilder sb = new StringBuilder(this.name);
if (ice) {
sb.append(" (ice)")
}
// other properties
return sb.toString()
}
最后几点注意事项:
ArrayList<Accessories> Accessoriesist
将是ArrayList<Accessories> accessoriesList
。 Properties
的enum
并让您的Accessories类包含一个List。 欢迎使用Java!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.