Sorting User Defined Collection Using Comparator

public class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", age=" + age + '}';
    }
}

 

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;


/**
 *
 * @author Shailesh Sonare
 */
public class MyCollections {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(0, 5);
        list.add(1, 2);
        list.add(2, 3);
        list.add(3, 8);
        
        Collections.sort(list, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }            
        });
        
        for(Iterator i = list.iterator(); i.hasNext();) {
            System.out.println("" + i.next());
        }
        
        
        Hashtable ht = new Hashtable();
        ht.put(0, "Shailesh Sonare");
        
        HashMap hm = new HashMap();
        hm.put(0, "Mahesh Sonare");
        
        ArrayList<Student> sl = new ArrayList<Student>();
        
        sl.add(new Student("Shailesh", 28));
        sl.add(new Student("Mahesh", 20));
        sl.add(new Student("Shilpa", 22));
        
        Collections.sort(sl, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.age > o2.age) {
                    return 1;
                } else if(o1.age < o2.age) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        
        for(Iterator i = sl.iterator(); i.hasNext();) {
            System.out.println((Student)i.next());
        }
        
    }
    
}

 

equals and hashcode

equals() method

The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.

hashCode() method

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

__________________________

A hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable.
Imagine the following simple example:
On the table in front of you you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible.
What you need is a way of instantly deciding which box you have put each object in. It works like an index; you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it.
Now imagine that you don’t want to bother with the index, you want to be able to find out immediately from the object which box it lives in.
In the example, let’s use a really simple way of doing this – the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on. What about the rhinoceros, though? It has 10 characters, so we’ll change our algorithm a little and “wrap round” so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object.
Sometimes a box will have more than one object in it, but if you are looking for a rocket, it’s still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas , banjos and rhinoceroses.
That’s a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java a hash code can be any integer, and each object type is responsible for generating its own. Lookup the “hashCode” method of Object.