1. Requirements: ArrayList remove duplicate values of strings in the collection (the contents of the string are the same)
Requirement: Cannot create a new collection, just do it on the previous collection.
2. code example:
1 Packagecn.itcast_04;2 3 Importjava.util.ArrayList;4 ImportJava.util.Iterator;5 6 /*7 * Requirement: ArrayList removes duplicate values of strings in the collection (the contents of the string are the same)8 * Requirements: You cannot create a new collection, just do it on the previous collection. 9 */Ten Public classArrayListDemo2 { One Public Static voidMain (string[] args) { A //To create a collection object -ArrayList array =NewArrayList (); - the //add multiple string elements (containing the same content) -Array.add ("Hello"); -Array.add ("World"); -Array.add ("Java"); +Array.add ("World"); -Array.add ("Java"); +Array.add ("World"); AArray.add ("World"); atArray.add ("World"); -Array.add ("World"); -Array.add ("Java"); -Array.add ("World"); - - //introduced by the idea of selective sequencing, we can do this with this idea. in //take the 0 index in turn and the back of the comparison, there will be after the kill - //Similarly, take 1 index ... to for(intx = 0; x < Array.size ()-1; X + +) { + for(inty = x + 1; Y < array.size (); y++) { - if(Array.get (x). Equals (Array.get (y))) { the array.remove (y); *y--; //When there are repeated additions to the element, there will be a slip through, so here to y--, re-judge $ }Panax Notoginseng } - } the + //iterating through the collection AIterator it =array.iterator (); the while(It.hasnext ()) { +String s =(String) It.next (); - System.out.println (s); $ } $ } -}
The results are as follows:
Java Basic Knowledge Hardening Collection Framework note 28:arraylist Collection exercises remove duplicate string elements from the ArrayList collection (upgrade)