use*_*634 2 java arraylist unchecked
我正在尝试将arraylists放入arraylist。将数据添加到新阵列,然后按顺序打印它们。我只是得到错误。
这是使用for循环在另一个arraylist中创建一个arraylist的正确方法吗?
现在,我还想了解如何以比这些长表达式更好的方式从数组中获取数据。
我的错误
jogging.java:101: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList
res.get(iter).add(new Resultat(name,time));
jogging.java:152: warning: [unchecked] unchecked conversion found : java.util.ArrayList required: java.util.List<T> Collections.sort(res.get(iter2));
jogging.java:152: warning: [unchecked] unchecked method invocation: <T>sort(java.util.List<T>) in java.util.Collections is applied to (java.util.ArrayList)
Collections.sort(res.get(iter2));
Run Code Online (Sandbox Code Playgroud)
导入java.util。;
导入java.lang。;
class Resultat implements Comparable<Resultat> {
String namn;
double tid;
public Resultat( String n, double t ) {
namn = n;
tid = t;
}
public String toString()
{
return namn + " "+ tid;
}
public int compareTo( Resultat r ) {
if (this.tid < r.tid){
return -1;
}
else if (this.tid > r.tid){
return 1;
}
else if (this.tid == r.tid && this.namn.compareTo(r.namn) <= 0)
{
return -1;
}
else if ( this.tid == r.tid && this.namn.compareTo(r.namn) >= 0){
return 1;
}
else {return 0;}
}
}
public class jogging {
public static void main( String[] args ){
int runners = scan.nextInt();
int competitions = scan.nextInt();
//create arraylist with arraylists within
ArrayList <ArrayList> res = new ArrayList<ArrayList>();
for(int i = 0; i <= competitions; ++i){
res.add(new ArrayList<Resultat>());
}
for (int i = 0; i < runners; i++){
String name = scan.next();
//runs the person made
int antalruns = scan.nextInt();
for(int n = 0; n <antalruns; n++){
//number of the run
int compnumber = scan.nextInt();
//time for the run
double time = scan.nextDouble();
for(int iter = 0; iter < res.size(); ++iter){
res.get(iter).add(new Resultat(name,time));
}
}
}
for(int iter2 = 0; iter2 < res.size(); ++iter2) {
Collections.sort(res.get(iter2));
System.out.println(iter2);
for(int it = 0; it < res.get(iter2).size(); ++it) {
System.out.println(res.get(iter2).get(it));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
未选中的警告是因为尚未声明第二个ArrayList的泛型类型。尝试使用
ArrayList <ArrayList<Resultat>> res = new ArrayList<ArrayList<Resultat>>();
Run Code Online (Sandbox Code Playgroud)
是的,这有点乏味。:-(
而且,大多数人认为最好使用左侧的接口(例如List,而不是ArrayList),以防万一您将来改变实现的想法。例如
List <List<Resultat>> res = new ArrayList<ArrayList<Resultat>>();
Run Code Online (Sandbox Code Playgroud)
添加
另外,您可以简化您的compareTo()方法。要比较这些提示,请查看Double.compare()。就像是:
public int compareTo( Resultat r ) {
int compare = Double.compare(tid, r.tod);
if (compare != 0)
return compare;
else
return namn.compareTo(r.namn);
}
Run Code Online (Sandbox Code Playgroud)