• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ArrayList question

 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I'm using an ArrayList in a servlet. I want to purge all the existing values by using the removeAll(collection) method. If I'm trying to remove all the existing values in this list...why do I need to specify a collection as an arguement?

Thanks,

Mike
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Collection.removeAll(Collection c) removes elements from "this" collection that are also in the passed in "c" collection. The full name should really be "removeElementsThatAreIn," but that's too much to type.

You're looking for Collection.clear(): "Removes all of the elements from this collection."
 
Mike Cunningham
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Excellent!!!

Thanks David.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the answer with an example

import java.util.*;
public class myArrLst {
public static void main(String[] ars) {
ArrayList arlst1 = new ArrayList();
ArrayList arlst2 = new ArrayList();

//lets add some elements
arlst2.add("4"); arlst2.add("5"); arlst2.add("6"); //Line X
arlst1.add("4"); arlst1.add("5"); arlst1.add("6");
arlst1.add(arlst1);

System.out.println("Size of list 1 " + arlst1.size());
System.out.println("Size of list 2 " + arlst2.size());

//Now the trick. There is recusrion that is build inside removeAll
arlst1.removeAll((Collection)arlst2); //removeAll belongs to interface
//Collection

System.out.println("Size of list 1 after removal" + arlst1.size());
System.out.println("Size of list 2 after removal" + arlst2.size());
}
}

//To see what happens in Line X change 4,5,6 to 1,2 & 3 respectively.

Hope this helps.

Caesar
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic