Here is the code with which i am experimenting.The output comes as expected
Khanna, Rahul
Malhotra, Ajay
Thakur, Ajay
Verma, Arun
One point to note is that if i set "103","48","65","75" in the lastname variable instead of the khanna,malhotra etc, then the output comes as
103, Rahul
48, Arun
65, Ajay
75, Ajay
i know it takes as 1<4/6/7.but the output is wrong,how to remove this discrepancy.
Code:-
package com.example;
import java.util.Arrays;
import java.util.ArrayList;
class Person implements Comparable
{
private String firstName;
private String lastName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this. lastName = lastName;
}
public int compareTo(Object o) throws ClassCastException
{
Person p = (Person)o;
if (!(o instanceof Person))
{
throw new ClassCastException("A Person object expected.");
}
int value = lastName.compareTo(p.lastName);
if (value == 0)
{
value = firstName.compareTo(p.firstName);
}
return value;
}
}
public class
Testing {
public static void main(String[] args)
{
Person[] persons = new Person[4];
persons[0] = new Person();
persons[0].setFirstName("Rahul");
persons[0].setLastName("Khanna");
persons[1] = new Person();
persons[1].setFirstName("Arun");
persons[1].setLastName("Verma");
persons[2] = new Person();
persons[2].setFirstName("Ajay");
persons[2].setLastName("Malhotra");
persons[3] = new Person();
persons[3].setFirstName("Ajay");
persons[3].setLastName("Thakur");
Arrays.sort(persons);
System.out.println();
System.out.println("Sorted by lastname........\n");
for (int i=0; i<4; i++)
{
Person person = persons[i];
String x = person.getLastName();
String y = person.getFirstName();
System.out.println(x + ", " + y );
}
}
}