【发布时间】:2021-03-04 13:30:19
【问题描述】:
我想为抽象类创建一个 Treeset。当我尝试打印树集中 [0] 的值时,输出正确地给出了1,但 [1] 的输出给出了错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
有人可以帮我解决这个问题吗?
public abstract class E implements Comparable<E>{
private int Id;
private String name;
public E(int Id, String name) {
this.Id = Id;
this.name = name;
}
int id;
public int compareTo(E b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
public int getId() {
return Id;
}
public String Name() {
return name;
}
}
【问题讨论】:
-
您需要决定要使用哪个 id,
empId或id。设置一个并检查另一个不起作用。 -
对不起,我不明白。我是使用 TreeSets 的新手。能详细点吗?
-
查看您的
Employee课程。您在构造函数中设置了empId,但在compareTo中使用了id。id从未被设置为任何值,因此被初始化为 0。 -
@MegCullen 注意:您可能希望为您的班级选择 E 以外的其他名称。您可能已经在菱形运算符中看到了 Comparable
或其他带有 E 或 T 的结构,但这并不意味着该类实际上被命名为“E”或“T”。更多信息在这里:docs.oracle.com/javase/tutorial/java/generics/types.html
标签: java arrays abstract-class treelist