Created
July 28, 2011 07:12
-
-
Save adaptives/1111136 to your computer and use it in GitHub Desktop.
Using the Set interface in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.diycomputerscience; | |
import java.util.HashSet; | |
import java.util.Iterator; | |
import java.util.Set; | |
import java.util.TreeSet; | |
public class JavaSet { | |
public static void main(String args[]) { | |
System.out.println("Adding words to a HashSet"); | |
Set<String> wordsInHashSet = createWordsInHashSet(); | |
System.out.println("Printing words from the HashSet"); | |
print(wordsInHashSet); | |
System.out.println(""); | |
System.out.println("Adding words to a TreeSet"); | |
Set<String> wordsInTreeSet = createWordsInTreeSet(); | |
System.out.println("Printing words from the TreeSet"); | |
print(wordsInTreeSet); | |
} | |
private static Set<String> createWordsInTreeSet() { | |
Set<String> set = new TreeSet<String>(); | |
set.add("one"); | |
set.add("two"); | |
set.add("three"); | |
set.add("four"); | |
set.add("five"); | |
set.add("three"); | |
return set; | |
} | |
private static Set<String> createWordsInHashSet() { | |
Set<String> wordsInHashSet = new HashSet<String>(); | |
wordsInHashSet.add("one"); | |
wordsInHashSet.add("two"); | |
wordsInHashSet.add("three"); | |
wordsInHashSet.add("four"); | |
wordsInHashSet.add("five"); | |
wordsInHashSet.add("three"); | |
return wordsInHashSet; | |
} | |
private static void print(Set<String> set) { | |
//Iterate across the Set and print it's contents | |
Iterator<String> iter = set.iterator(); | |
while(iter.hasNext()) { | |
String word = iter.next(); | |
System.out.println(word); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment