简体   繁体   English

同时从JTable和Hashmap中删除项目

[英]Removing item from JTable and Hashmap at the same time

I'm writing a simple java application and trying to add a feature to add/remove a school "Class". 我正在编写一个简单的Java应用程序,并尝试添加功能以添加/删除学校的“班级”。

I have a Hashmap to store each Class. 我有一个哈希图来存储每个类。 The class object has a name (String) and # of criteria (int). 类对象具有名称(字符串)和条件编号(整数)。 When I add the Class object to my Hashmap I also add the Class name and criteria to a JTable. 当我将Class对象添加到Hashmap时,我还将Class名称和条件添加到JTable中。

The problem comes in when trying to remove a Class. 尝试删除类时出现问题。 I can easily remove it from the JTable by getting the selected item, and removing it; 我可以很容易地从JTable中删除它,方法是获取选定的项目并将其删除; however, I can't remove the Class from my Hashmap by name or criteria alone, because some classes may have the same name, or same number of criteria. 但是,我不能仅通过名称或条件从Hashmap中删除该类,因为某些类可能具有相同的名称或相同数量的条件。 I've tried adding a unique class ID to each class so I can remove it like that, but it isn't nice to look at the class ID in the JTable. 我尝试为每个类添加一个唯一的类ID,这样就可以将其删除,但是在JTable中查看该类ID并不好。

Is there a better way to do all this? 有没有更好的方法来完成所有这些工作? Thank you. 谢谢。

Well if you wanted to store the classes within a JTable I would presume they'd be kept in some ordered form. 好吧,如果您想将类存储在JTable中,我想它们会以某种有序的形式保存。 If that's the case then it would be much simpler to store them in a List<Class> instead of mapping them. 如果真是这样,那么将它们存储在List<Class>而不是映射它们将简单得多。

Essentially maps are used to store objects using a Key to be used at a later point regardless of the map's order. 本质上,地图用于存储使用Key对象,以便以后使用,而不管地图的顺序如何。

You can store Class name and # of criteria as fields within Class and store that object inside a List. 您可以存储类名和标准为内场# Class ,一个列表内的对象和存储。 After that you can easily add/remove the Class from JTable & List simultaneously which will save you alot of unnecessary hassle by using List#add() and List#remove . 之后,您可以轻松地同时从JTableList添加/删除Class ,这将通过使用List#add()List#remove节省许多不必要的麻烦。

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

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