简体   繁体   English

Java DefaultListModel包含奇怪元素的问题

[英]Java DefaultListModel weird element-containing issue

I am writing a Java application with swing components. 我正在编写带有swing组件的Java应用程序。 I have 2 JLists which get their data from a DefaultListModel, being these 2: 我有2个JList,它们是从DefaultListModel中获取数据的,它们是这些2:

private DefaultListModel<Module> moduleListModel;
private DefaultListModel<Module> sem1ListModel;

Module is a dataclass I have created. 模块是我创建的数据类。

Now the problem is, I want to remove Modules from my moduleListModel, if they are also in the sem1ListModel. 现在的问题是,如果它们也在sem1ListModel中,我想从我的moduleListModel中删除它们。 I know there are 3 modules in sem1ListModel which are also in the defaultListModel, and the code I use to check if it contains them is: 我知道sem1ListModel中有3个模块,它们也在defaultListModel中,我用来检查是否包含它们的代码是:

for(int i = 0; i < sem1ListModel.getSize(); i++){
        Module mod = sem1ListModel.getElementAt(i);
                    System.out.println(mod);
        if(moduleListModel.contains(mod)){
            System.out.println(mod);
            moduleListModel.removeElement(mod);
        }
    }

This code should be working, as the Modules are both exactly the same, yet it doesn't! 该代码应该可以正常工作,因为两个模块完全相同,但事实并非如此! When I print both DefaultListModel to the output window, I get this: 当我将两个DefaultListModel都打印到输出窗口时,得到以下信息:

    System.out.println(sem1ListModel);
    System.out.println(moduleListModel);

sem1ListModel: [Software development 1 [7 credits], ICT Management 1 [7 credits], DOA I [6 credits]] moduleListModel: [DOA I [6 credits], Software development 1 [7 credits], ICT Management 1 [7 credits], Webdesign 2 [5 credits], Software 1 [5 credits]] sem1ListModel: [软件开发1 [7学分],ICT管理1 [7学分],DOA I [6学分]] moduleListModel: [DOA I [6学分],软件开发1 [7学分],ICT管理1 [7学分] ],网页设计2 [5学分],软件1 [5学分]]

As you can see, Software development 1 [7 credits], ICT Management 1 [7 credits], DOA I [6 credits] are the 3 Modules which are in both DefaultListModels and should be deleted from moduleListModel, yet this doesn't happen. 如您所见, 软件开发1 [7学分],ICT管理1 [7学分],DOA I [6学分]是两个DefaultListModels中的3个模块,应将其从moduleListModel中删除,但这不会发生。

What am I doing wrong? 我究竟做错了什么?

I'll just make an answer from the comments so this doesn't hang about. 我只是从评论中回答,所以这不会挂在嘴边。

The problem is that the Module objects are in fact different instances, and did not have equals overridden. 问题在于, Module对象实际上是不同的实例,并且没有覆盖equals This means that, even though they printed the same thing via the overridden toString , the model treated them as distinct objects and did not perform the removal. 这意味着,即使它们通过重写的toString打印了相同的内容,模型也会将它们视为不同的对象,并且不会执行删除操作。

The standard way to fix this is to override equals (and hashCode in case you ever want to use a hashing data structure). 解决此问题的标准方法是覆盖equals (和hashCode ,以防您想使用哈希数据结构)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM