Interview Questions

Java Keywords
Key Concepts
OOPS in java
Java Collections#1
Java Collections #2
Exceptions #1
Exceptions #2
Threads#1
Threads#2
InnerClass
Serialization
Immutable Class
Cloning in Java
Garbage Collection
JSP #1
JSP #2
Programming Q#1
Programming Q#2
Programming Q#3


Sort a collection.

Consider a model class Person with property name,age and date of birth.


 
 class Person {

 public String name;
 public int age;
 public Date dob;
 }
Consider a list of Person object. There are two ways to sort the list . Using Comparator or Comparable.
 
 public sortList()  {

   	List<Person> personList = getListofPerson(); // some method to get the list.
   	//sort by name;
   Collections.sort(personList, new Comparator<Person>() {
           public int compare(Person e1, Person e2) {
               return e2.name.compareTo(e1.name);
   		}});
   // sort by age
	
   	Collections.sort(personList, new Comparator<Person>() {
           public int compare(Person e1, Person e2) {
    			if (e1.age > e2.age )
    			return 1;
    			if (e1.age < e2.age)
    			 return -1;
    			else
    				return 0;
   		}});
 }