package datastructures;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
public class Sets {
public static void main(String[] args) {
// hashset is random order
Set animals = new HashSet();
animals.add("dog");
animals.add("pig");
animals.add("hog");
animals.add("cow");
System.out.println(animals);
animals.add("hog");
animals.add("cow");
animals.add("groose");
// same elements does not add again
System.out.println(animals);
// linked hash set is same order in added
Set animals1 = new LinkedHashSet();
animals1.add("chicken");
animals1.add("pig");
animals1.add("snake");
animals1.add("cow");
System.out.println(animals1);
// Difference of animals from animals1
Set differenceSet = new HashSet(animals);
differenceSet.removeAll(animals1);
System.out.println(differenceSet);
// Union of animals from animals1
Set unionSet = new HashSet(animals);
unionSet.addAll(animals1);
System.out.println(unionSet);
// tree set is in alphabetical order
Set animals2 = new TreeSet();
animals2.add("dog");
animals2.add("pig");
animals2.add("hog");
animals2.add("cow");
System.out.println(animals2);
}
}
Here is the output:
[hog, cow, dog, pig]
[groose, hog, cow, dog, pig]
[chicken, pig, snake, cow]
[groose, hog, dog]
[groose, hog, chicken, snake, cow, dog, pig]
[cow, dog, hog, pig]
Hiç yorum yok:
Yorum Gönder