Would you like to react to this message? Create an account in a few clicks or log in to continue.

implements Comparable Ѻѹ Sort

Go down

 implements  Comparable Ѻѹ Sort  Empty implements Comparable Ѻѹ Sort

ตั้งหัวข้อ  Admin Thu May 22, 2008 2:22 pm


class Person implements Comparable {
private String firstName;
private String lastName;
private int age;

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 getAge() {
return age;
}

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

public int compareTo(Object anotherPerson) throws ClassCastException {
if (!(anotherPerson instanceof Person))
throw new ClassCastException("A Person object expected.");
int anotherPersonAge = ((Person) anotherPerson).getAge();

return this.age - anotherPersonAge; // §ҡҡ

//
return anotherPersonAge-this.age; // §ҡҡ

}

}




package comparable;

import java.util.Arrays;

public class Testing {

public static void main(String[] args) {
Person[] persons = new Person[4];
persons[0] = new Person();
persons[0].setFirstName("Elvis");
persons[0].setLastName("Goodyear");
persons[0].setAge(56);

persons[1] = new Person();
persons[1].setFirstName("Stanley");
persons[1].setLastName("Clark");
persons[1].setAge(56);

persons[2] = new Person();
persons[2].setFirstName("Jane");
persons[2].setLastName("Graff");
persons[2].setAge(16);

persons[3] = new Person();
persons[3].setFirstName("Nancy");
persons[3].setLastName("Goodyear");
persons[3].setAge(69);

System.out.println("Natural Order");

for (int i=0; i<4; i++) {
Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}

Arrays.sort(persons);

System.out.println();
System.out.println("Sorted by age");

for (int i=0; i<4; i++) {
Person person = persons[i];
String lastName = person.getLastName();
String firstName = person.getFirstName();
int age = person.getAge();
System.out.println(lastName + ", " + firstName + ". Age:" + age);
}
}
}



Admin
Admin
Admin

จำนวนข้อความ : 112
Registration date : 18/05/2008

http://chawban.chocoforum.com

ขึ้นไปข้างบน Go down

ขึ้นไปข้างบน

- Similar topics

 
Permissions in this forum:
คุณไม่สามารถพิมพ์ตอบ