HashSets
With HashSet with have no duplicates, but we loose sorting.
/**
* HashSet have no duplicates, but no sorting.
*/
package com.minte9.collections.sets;
import java.util.HashSet;
public class HashSets {
public static void main(String[] args) {
HashSet<Song> mySet = new HashSet<Song>();
mySet.add(new Song("A", "2"));
mySet.add(new Song("C", "1"));
mySet.add(new Song("B", "4"));
mySet.add(new Song("B", "3"));
System.out.println(mySet); // [A:2, B:3, C:1]
// no duplicates
// hash code
/*
65
67
66
66
*/
}
}
class Song implements Comparable<Song>{
public String title;
public String artist;
@Override public boolean equals(Object o) {
Song s = (Song) o;
return title.equals(s.title); // Look Here
}
@Override public int hashCode() {
return title.hashCode(); // Look Here
}
@Override public int compareTo(Song s) {
return title.compareTo(s.title);
}
public Song(String t, String a) {
title = t;
artist = a;
}
@Override public String toString() {
return title + ":" + artist;
}
}
Trees
TreeSet prevents duplicates and keeps the list sorted.
/**
* TreeSet is similar to HashSet in that it prevents duplicates.
* But it also keeps the list sorted (very small performance hit).
*/
package com.minte9.collections.sets;
import java.util.ArrayList;
import java.util.TreeSet;
public class TreeSets {
public static void main(String[] args) {
ArrayList<A> myList = new ArrayList<>();
myList.add(new A("F", "1"));
myList.add(new A("G", "2"));
myList.add(new A("H", "4"));
myList.add(new A("H", "3"));
TreeSet<A> myTree = new TreeSet<A>();
myTree.addAll(myList);
System.out.println(myTree); // [F:1, G:2, H:4]
}
}
class A implements Comparable<A> {
public String title;
public String artist;
public A(String t, String a) {
title = t;
artist = a;
}
@Override public int compareTo(A a) {
return title.compareTo(a.title);
}
@Override public String toString() {
return title + ":" + artist;
}
}
Last update: 473 days ago