1. Remove duplicate string elements from the ArrayList collection (same string content)
Analysis:
(1) Creating a Collection Object
(2) Adding multiple string elements (containing duplicates)
(3) Create a new collection
(4) Iterate through the old collection to get each element
(5) Take an element to the new set and look for it.
Have: ignore it
No: Add to new collection
(6) Traversing a new collection
2. Case code:
1 Packagecn.itcast_04;2 3 Importjava.util.ArrayList;4 ImportJava.util.Iterator;5 6 /*7 * ArrayList removes duplicate values of strings in the collection (the contents of the string are the same)8 * 9 * Analysis:Ten * A: Create A Collection Object One * B: Add multiple string elements (containing the same content) A * C: Create a new collection - * D: Traverse old collection, get each element - * E: Take this element to the new collection to find out, see if there is the * have: ignore it - * No: Add to new collection - * F: Traverse new Collection - */ + Public classArraylistdemo { - Public Static voidMain (string[] args) { + //To create a collection object AArrayList array =NewArrayList (); at - //add multiple string elements (containing the same content) -Array.add ("Hello"); -Array.add ("World"); -Array.add ("Java"); -Array.add ("World"); inArray.add ("Java"); -Array.add ("World"); toArray.add ("World"); +Array.add ("World"); -Array.add ("World"); theArray.add ("Java"); *Array.add ("World"); $ Panax Notoginseng //Create a new collection -ArrayList NewArray =NewArrayList (); the + //iterate through the old collection, get each element AIterator it =array.iterator (); the while(It.hasnext ()) { +String s =(String) It.next (); - $ //take this element to the new collection and look for it. $ if(!Newarray.contains (s)) { - Newarray.add (s); - } the } - Wuyi //Traverse a new collection the for(intx = 0; x < Newarray.size (); X + +) { -String s =(String) newarray.get (x); Wu System.out.println (s); - } About } $}
The results are as follows:
Java Basic Knowledge Hardening Collection Framework note 27:arraylist collection exercises to remove duplicate string elements from the ArrayList collection