Tuesday, November 07, 2006

LinkedHashSet and HashSet


package justtest;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class TestSet {

public static void main(String[] args) {

/** Create set that retains Order-of-Insertion */
Set set = new LinkedHashSet();
set.add("1");
set.add("2");
set.add("3");
set.add("2");
for (Iterator it = set.iterator(); it.hasNext();) {
System.out.println(it.next()); //1,2,3
}

/** Create set that does not retain Order-of-Insertion */
Set set2 = new HashSet();
set2.add("1");
set2.add("2");
set2.add("3");
set2.add("2");
set2.add("3");
for (Iterator it = set2.iterator(); it.hasNext();) {
System.out.println(it.next()); //3,2,1
}
}
}

0 Comments:

Post a Comment

<< Home