Put your own type in a LinkedHashSet in Java

Description

The following code shows how to put your own type in a LinkedHashSet.

Example


/*from   w  w w. ja va  2  s  . c  o  m*/
import java.util.LinkedHashSet;
import java.util.Set;

public class Main {

  public static Set fill(Set a, int size) {
    for (int i = 0; i < size; i++)
      a.add(new MyType(i));
    return a;
  }

  public static void test(Set a) {
    fill(a, 10);
    fill(a, 10); // Try to add duplicates
    fill(a, 10);
    System.out.println(a);
  }

  public static void main(String[] args) {
    test(new LinkedHashSet());
  }
}

class MyType implements Comparable {
  private int i;

  public MyType(int n) {
    i = n;
  }

  public boolean equals(Object o) {
    return (o instanceof MyType) && (i == ((MyType) o).i);
  }

  public int hashCode() {
    return i;
  }

  public String toString() {
    return i + " ";
  }

  public int compareTo(Object o) {
    int i2 = ((MyType) o).i;
    return (i2 < i ? -1 : (i2 == i ? 0 : 1));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet