【发布时间】:2020-06-10 10:26:42
【问题描述】:
所以我有这个任务,我需要将数据放入树集中。我有三个班级:
-
兄弟.java。赋值说构造函数是不公开的,所以我使用getInstance()来初始化Brother对象
public class Brother { String name; int day; int month; private static Brother instance = null; private Brother() { name = "0"; day = 0; month = 0; } public static Brother getInstance() { if(instance == null) { instance = new Brother(); } return instance; } } -
家庭班。该类用于将兄弟对象分配到以兄弟为对象的树集中。
import java.util.Set; import java.util.TreeSet; public class Family { Set<Brother> Brothers; public Family() { this.Brothers = new TreeSet<Brother>(); } public Brother makeBrother() { Brother B = Brother.getInstance(); return B; } public boolean addBrother(String name, int day, int month) { Brother B = Brother.getInstance(); return Brothers.add(B); } } -
最后是主类
public class Main { public static void main(String[] args) { Family myFamily = new Family(); myFamily.makeBrother(); // myFamily.addBrother("Shane", 3, 2); } }
每当我尝试使用 myFamily.addBrother() 时,我总是收到此错误“线程“main”java.lang.ClassCastException 中的异常:类 Brother 无法转换为类 java.lang.Comparable(Brother 位于未命名的模块中) loader 'app'; java.lang.Comparable 在 loader 'bootstrap' 的模块 java.base 中)”。我和那有什么关系?当我使用 myFamily.makeBrother() 时,该程序非常好。该算法尚未全部完成,但是当我尝试运行它时,这发生在我身上,我无法继续下一步。之前谢谢你。
【问题讨论】:
标签: java collections treeset