Title: Set Examples
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Set Examples

I want to compare some "Collection Interface" methods between HashSet, LinkedHashSet, TreeSet and ArrayList.

I want to show you what is good about the classes which implement the Set interface ... they should be fast with the method:

boolean contains(Object)

We are going to generate random numbers and we would like to only store unique numbers generated.

The following code will need Timer.java

ContainsPerformance.java


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.TreeSet;


class MyNumber implements Comparable<MyNumber>
{
    static int MaxNumber = 20000000; // 20 million
    int value;
    int iteration;
    MyNumber(int iteration)
    {
        value = (int)(MaxNumber * Math.random());
        this.iteration = iteration;
    }
    public boolean equals(Object ob)
    {
        MyNumber n = (MyNumber)ob;
        if (value == n.value )
            return true;
        else
            return false;
    }
    public String toString()
    {
        return value +":"+ iteration;
    }
    public int hashCode()
    {
        return value;
    }
    @Override
    public int compareTo(MyNumber other) {
        return value - other.value;
    }
}



public class ContainsPerformance {
    static void addManyObjects(int N, Collection<MyNumber> collection)
    {
        Timer timer = new Timer();
        timer.start();
        for (int i=0; i < N; i++)
        {
            MyNumber myNumber = new MyNumber(i);
            if (!collection.contains(myNumber))
                collection.add(myNumber);
        }
        timer.stop();

	     System.out.println(collection.size() + " numbers stored");
        collection.clear();  // Free up memory for next test
        System.out.printf("time elapsed = %.4f  seconds%n" , timer.time());
    }


    public static void main(String[] args) {

        System.out.println("Enter in N (recommend 2000000 or 60000):");
        Scanner keyboard = new Scanner(System.in);
        int N = keyboard.nextInt();

        System.out.println("Try HashSet(3000000):");
        HashSet<MyNumber> hashSet = new HashSet<MyNumber>(3000000);
        addManyObjects(N, hashSet);

        System.out.println("Try HashSet:");
        HashSet<MyNumber> hashSet2 = new HashSet<MyNumber>();
        addManyObjects(N, hashSet2);


        System.out.println("Try LinkedHashSet:");
        LinkedHashSet<MyNumber> linkedHashSet = new LinkedHashSet<MyNumber>();
        addManyObjects(N, linkedHashSet);

        System.out.println("Try TreeSet:");
        TreeSet<MyNumber> treeSet = new TreeSet<MyNumber>();
        addManyObjects(N, treeSet);

        System.out.println("Try ArrayList:");
        ArrayList<MyNumber> arrayList = new ArrayList<MyNumber>();
        addManyObjects(N, arrayList);

        keyboard.close();
    }

}



Union and Intersection methods

Create a new class derived from HashSet which provides Union and Intersection methods that work according to a Mathematicians ideas of Sets. Create a sample main to try out your new class (use String as the Element type). Note that the HashSet order can be random.



import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


// Change the HashSet to LinkedHashSet
// Change the HashSet to TreeSet

public class MathSet<T> extends HashSet<T> {

    Set<T> union(Set <T> other)
    {
        Set<T> union = new MathSet<T>();

        Iterator<T> iter = iterator();
        while (iter.hasNext())
        {
            union.add(iter.next());
        }

        iter = other.iterator();
        while (iter.hasNext())
        {
            // We don't have to check if it's there
            // because a Set will only add a unique
            // item once.
            union.add(iter.next());
        }


        return union;
    }

    Set<T> intersection (Set<T> other)
    {
        Set<T> intersection = new MathSet<T>();

        Iterator<T> iter = iterator();
        while (iter.hasNext())
        {
            T obj = iter.next();
            if (other.contains(obj))
                intersection.add(obj);
        }
        return intersection;
    }

    public static void dump(Set<String> s)
    {
        Iterator<String> iter = s.iterator();
        while (iter.hasNext())
            System.out.println(iter.next());
    }


    public static void main(String[] args) {
        MathSet<String> mySet1 = new MathSet<String>();
        MathSet<String> mySet2 = new MathSet<String>();

        mySet1.add("Michigan");
        mySet1.add("Ohio");
        mySet1.add("Indiana");
        mySet1.add("Kentucky");

        mySet2.add("Michigan");
        mySet2.add("Ohio");
        mySet2.add("Indiana");
        mySet2.add("Texas");
        mySet2.add("Alaska");

        Set<String> union = mySet1.union(mySet2);
        Set<String> intersection = mySet1.intersection(mySet2);

        System.out.println(" *********  Intersection ***********");
        dump(intersection);
        System.out.println(" *********  Union ***********");
        dump (union);
    }
}


Last Updated: November 10, 2013 0:23 AM