Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Things you can do with Sets

import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; public class MainClass {   static void fill(Set s) {     s.addAll(Arrays.asList("one two three four five six seven".split(" ")));   }   public static void test(Set s) {     System.out.println(s.getClass().getName().replaceAll("\\w+\\.", ""));     fill(s);     System.out.println(s); // No duplicates!     s.addAll(s);     s.add("one");     System.out.println(s);     System.out.println("s.contains(\"one\"): " + s.contains("one"));   }   public static void main(String[] args) {     test(new HashSet());     test(new TreeSet());     test(new LinkedHashSet());   } } HashSet [one, two, five, four, three, seven, six] s.contains("one"): true TreeSet [five, four, one, seven, six, three, two] s.contains("one"): true LinkedHashSet [one, two, three, four, five, six, seven] s.contains("one"): true