posted 22 years ago
Thanks Neil,
The following code does sort by length of string instead ascending order.Eg. I put August 13, August 9, August 2. It will sort like August 13, August 2, August 9 instead August 2, August 9, August 13.
Would you please help me out? If you need to view code:
Code for NameSort.java:
import java.util.*;
class NameSort {
public static void main(String args[]) {
Name [] n= new Name[4];
n[0] = new Name("10", "Rakeh", "Pandit");
n[1] = new Name("20","Rakesh", "Pandit");
n[2] = new Name("90","Angela", "Desouza");
n[3] = new Name("100", "Ed", "Lin");
List set = new ArrayList();
set.add(n[0]);
set.add(n[1]);
set.add(n[2]);
set.add(n[3]);
Collections.sort(set,Name.FIRST);
ListIterator it = set.listIterator();
while(it.hasNext()){
Name name = (Name)it.next();
System.out.println(name.lastName + " " + name.firstName);
}
}
}
Code for Name.java:
import java.util.*;
class Name
{
public String number, firstName, lastName;
public Name(String number,String firstName, String lastName)
{
if (firstName==null || lastName==null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
}
public static final Comparator FIRST = new Comparator()
{
public int compare(Object o1, Object o2)
{
try
{
Name name1 = (Name)o1;
Name name2 = (Name)o2;
return name1.firstName.compareTo(name2.firstName);
}
catch(ClassCastException e)
{
// do something here
}
return 0;
}
// do something for equals too
};
public static final Comparator LAST = new Comparator()
{
public int compare(Object o1, Object o2)
{
try
{
Name name1 = (Name)o1;
Name name2 = (Name)o2;
return name1.lastName.compareTo(name2.lastName);
}
catch(ClassCastException e)
{
// do something here
}
return 0;
}
// do something for equals too
};
public static final Comparator NUMBER = new Comparator()
{
public int compare(Object o1, Object o2)
{
try
{
Name name1 = (Name)o1;
Name name2 = (Name)o2;
return name1.number.compareTo(name2.number);
}
catch(ClassCastException e)
{
// do something here
}
return 0;
}
// do something for equals too
};
}
Please help me out.
Thanks,
Angela