Skip to Main Content

Java HotSpot Virtual Machine

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

sorting a collection of any type object

843829Apr 19 2006 — edited Apr 20 2006
hi all,
I had to show a list in sorting order, ofcoursce that can be done
by, Collections.sort(collectionObj);
the 'collectionObj' will be sorted in lexical order if it contains String Object
but what if the collectionObj contains 'Myclass' Objects
MyClass{
FIrstName;
LastName;
Middle;
---------
String toString(){
return FIrstName;
}
}

and i wont to sort the collection by Firstname
for this i tried out like this
i wrote a class
public class MyComparator implements Comparator{

boolean isInteger=false;
public MyComparator(){
	
}

public MyComparator(boolean isInteger){
	this.isInteger=isInteger;
}

 public int compare(Object o1, Object o2){
 	String s1=o1.toString();
String 	s2=o2.toString();
 	if(!isInteger){

   return s1.compareTo(s2.toLowerCase());
 	}else{
 		int i1=Integer.parseInt(s1);
 		int i2=Integer.parseInt(s2);
 		 return i1-i2;
 	}
   
  
}

public boolean equals(Object obj){
  return true;	
}
}


now, for sorting
collectionObj.add(MyClassObj1);
collectionObj.add(MyClassObj2);
collectionObj.add(MyClassObj3);
Collections.sort(collectionObj,new Mycomparator());

to sort AnotherClass objects say bye age
Collections.sort(collectionObj,new Mycomparator(true));

now my question is
1)how can i sort by alpha numeric attributes of objects
2)and how can i sort the Myclass object now by lastname, since i overwritten toString() method with firstname now i need to change to lastname but this is not appropriate because what if i want to sort by middlename.
how could i sovle this problem with just 1 Comparator implemented class
and this class should solve String, numerics, alpha numerics

suggestion please
with regards
satya
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 18 2006
Added on Apr 19 2006
7 comments
307 views