简体   繁体   中英

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".

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.

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; 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. 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.

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. If that's the case then it would be much simpler to store them in a List<Class> instead of mapping them.

Essentially maps are used to store objects using a Key to be used at a later point regardless of the map's order.

You can store Class name and # of criteria as fields within Class and store that object inside a List. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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