wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Remove a subset of objects at once Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Remove a subset of objects at once" Watch "Remove a subset of objects at once" New topic
Author

Remove a subset of objects at once

xeon costa
Greenhorn

Joined: May 10, 2011
Posts: 15

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?



Thanks,
Pranav Raulkar
Ranch Hand

Joined: Apr 20, 2011
Posts: 73

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

Joined: May 10, 2011
Posts: 15

Synchronization is an issue.
Pranav Raulkar
Ranch Hand

Joined: Apr 20, 2011
Posts: 73

Then use HashTable as it is synchronized.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Remove a subset of objects at once
 
Similar Threads
one question about gc?
Cross Reference two ArrayList Duplicates Removal
Sorting using Comparable interface
Compare two lists
Jdiscuss question of the day - April 3, 2005