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
How the metacharacters are different from the ordinary characters?
These static constructors are correct ? class A { statc intA() { } static A(int x,int y) { } static A(int x) { } }
What is hash in java?
Can an arraylist be empty?
State the difference between creating string as new () and literal.
If a variable is declared as private, where may the variable be accessed?
What data type is true or false?
Is it possible for a yielded thread to get chance for its execution again?
What is the difference between == and === javascript?
What is the meaning of variable in research?
In how many ways we can create threads in java?
Why map is used in java?
What is the use of protected in java?
Is 64bit faster than 32 bit?
What is bitwise complement?