【问题标题】:ArrayIndexOutOfBoundsException while printing a TreeSet打印 TreeSet 时出现 ArrayIndexOutOfBoundsException
【发布时间】: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,empIdid。设置一个并检查另一个不起作用。
  • 对不起,我不明白。我是使用 TreeSets 的新手。能详细点吗?
  • 查看您的Employee 课程。您在构造函数中设置了empId,但在compareTo 中使用了idid 从未被设置为任何值,因此被初始化为 0。
  • @MegCullen 注意:您可能希望为您的班级选择 E 以外的其他名称。您可能已经在菱形运算符中看到了 Comparable 或其他带有 E 或 T 的结构,但这并不意味着该类实际上被命名为“E”或“T”。更多信息在这里:docs.oracle.com/javase/tutorial/java/generics/types.html

标签: java arrays abstract-class treelist


【解决方案1】:

在 Employee 类中的 compareTo 方法中,您应该比较 empId,而不是您创建但从未初始化的这个 int id。

【讨论】:

  • 使用 empId 代替 id 有效。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2014-03-16
  • 2011-08-05
  • 2014-12-27
  • 2014-11-25
  • 2015-12-22
  • 2021-12-19
  • 2017-05-06
  • 2015-10-16
相关资源
最近更新 更多