Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Remove a subset of objects at once

 
xeon costa
Greenhorn
Posts: 15
Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I've an ArrayList of Obejcts, and I would like to remove a subset of Objects at once. The problem is that, when I iterate over an Arraylist, and I remove an Object, the other objects are reallocated, and son it's impossible to remove a subset of objects at once. Each Object contains a id.

Here's an example:

I've a list with Objects:
List {Obj1, Obj2, Obj3, Obj4, Obj5}.

And now I would like to remove Obj2 and Obj5 at once.

Probably the ArrayList is not the best Collection to do that, but what other collection should I use?


 
Pranav Raulkar
Ranch Hand
Posts: 73
Android Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If synchronization is not an issue, then use HashMap or else use HashTable. Both store data in (key,value) pairs. In your case key can be your object's ID and value is the object itself. So to delete an entry (object) all you need to do is call remove(key) specifying the key of the object that you want to delete. Also you can use containsKey(key) to check if indeed there is an entry with the specified key in the HashTable/HashMap. Also remember HashTable doesnt allow null values.
 
xeon costa
Greenhorn
Posts: 15
Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronization is an issue.
 
Pranav Raulkar
Ranch Hand
Posts: 73
Android Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then use HashTable as it is synchronized.
 
Rob Spoor
Sheriff
Pie
Posts: 20526
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need a Map for this at all. ArrayList has method removeAll, like all Collection implementations, and you can pass any Collection to it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic