大家好今天我想在我的ArrayList中尝试这样做,我知道这是可能的,但它在main上给了我一个例外。现在我想知道我是怎么做错的或者最好的方法是什么。我试图拥有一个ArrayList并在ArrayList中我有另一个,我给它一个变量。
<%= render partial: "users", locals: { users: @users, style: "col-sm-2 col-xs-12" } %>
现在吼叫是我的家庭班,在我的家庭中,这是价值
import java.util.ArrayList;
import java.util.Collection;
public class Example3 {
public static void main(String[] args) {
ArrayList<ArrayList<Family>> smallFamily = new ArrayList<ArrayList<Family>>();
smallFamily.addAll((Collection<? extends ArrayList<Family>>) (new Family("John",89 )));
smallFamily.addAll((Collection<? extends ArrayList<Family>>) new Family ("Smith", 78)));
for(ArrayList<Family> s: smallFamily){
System.out.println(s);
}
}
编译和运行程序时抛出的异常是
public class Family {
public String Name;
public int weight;
public Family(String Name, int weight){
this.Name = Name;
this.weight = weight;
}
public String toString(){
return ("The name is " + this.Name + "The weight is: " + this.weight);
}
}}
现在我自己学习Java,没有任何我可以问的问题。任何形式的帮助将不胜感激。
答案 0 :(得分:2)
您正在尝试将对象转换为集合。这不起作用。相反,你需要这样做:
smallFamily.add(new ArrayList<Family>(1) {{add(new Family("", 0));}});
这将创建ArrayList
,在创建时添加new Family("", 0)
。然后,它会将这个arraylist添加到smallFamily arraylist。
答案 1 :(得分:0)
现在为什么你在这里得到这一行
smallFamily.addAll((Collection<? extends ArrayList<Family>>) (new Family("John",89 )));
只是因为计算机无法理解你在做什么所以它是为你铸造的。或者你铸造了:)。现在尝试将对象转换为集合不起作用。
相反,你需要尝试这个
public class Example3 {
public static void main(String[] args) {
ArrayList<ArrayList<Family>> smallFamily = new ArrayList<ArrayList<Family>>();
smallFamily.add(new ArrayList<Family>(2222) {{add(new Family("smith ", 0));}});
smallFamily.add(new ArrayList<Family>(333) {{add(new Family("john ", 0));}});
for(ArrayList<Family> s: smallFamily){
System.out.println(s);
}
}
}
添加家庭等级
public class Family {
public String Name;
public int weight;
public Family(String Name, int weight){
this.Name = Name;
this.weight = weight;
}
public String toString(){
return ("The name is " + this.Name + "The weight is: " + this.weight);
}
}
输出应为
[The name is smith The weight is: 0]
[The name is john The weight is: 0]
希望这就是你所期待的。