微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

打印 TreeSet 时出现 ArrayIndexOutOfBoundsException

如何解决打印 TreeSet 时出现 ArrayIndexOutOfBoundsException

我想为抽象类创建一个树集。当我尝试打印树集中 [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;
    }   
  }

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。