How to sort a vector elements that contains the user define
class object? (Note: If Suppose consider, A Student class
contain two data members. They are String studentName and
int rollNo. I am creating Four objects for this class, each
object contains students details like name and roll no. Now
i am storing that objects in vector and if i retiving the
elements from the vector means then it should be display in
sorting order)

Answer Posted / naren reddy

For sorting Any user defined class,We need to implement the
userdefined class with comparable or comparator
interfcae.Then only your collections.sort(ArrayList al)
will work,Otherwise it won't work.


Ex: class Employee implements Comparable{

private int age;

public void setAge(int age){
this.age=age;
}

public int getAge(){
return this.age;
}public int compareTo(Object otherEmployee){

/*
If passed object is of type other than Employee,
throw ClassCastException.
*/

if(!(otherEmployee instanceof Employee)){
throw new ClassCastException("Invalid object");
}

int age = ((Employee) otherEmployee).getAge();

if(this.getAge() > age)
return 1;
else if ( this.getAge() < age )
return -1;
else
return 0;

}

}

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the two parts of a conditional statement?

741


How do you create an array in java?

765


What are parameters in a method?

811


What one should take care of, while serializing the object?

685


When do you get classcastexception?

794


Why super is first line in java?

837


How do you check if two given string are anagrams?

743


Why we cannot override static method?

777


Explain method local inner classes ?

811


Can an interface extend another interface?

828


Explain the difference between throw and throws in java?

785


Which command from the jdk compiles a java program?

691


What does g mean in regex?

760


What is ++ a in java?

774


What are white spaces in java?

763