package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PersonComparable implements Comparable<PersonComparable> {
private int age;
private String firstName;
private String secondName;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
@Override
public int compareTo(PersonComparable personComparable) {
int compareAge = ((PersonComparable) personComparable).getAge();
return this.age - compareAge;
}
public static void main(String args[]) {
PersonComparable person = new PersonComparable();
person.setAge(65);
person.setFirstName("Kumar");
person.setSecondName("Bhatia");
PersonComparable personOne = new PersonComparable();
personOne.setAge(35);
personOne.setFirstName("Ashish");
personOne.setSecondName("Bhambhani");
PersonComparable personTwo = new PersonComparable();
personTwo.setAge(45);
personTwo.setFirstName("Sameer");
personTwo.setSecondName("Kulkarni");
List<PersonComparable> persons = new ArrayList<PersonComparable>();
persons.add(person);
persons.add(personOne);
persons.add(personTwo);
Collections.sort(persons);
for (PersonComparable comparable : persons) {
System.out.println(comparable.getAge());
}
}
}
Friday, May 31, 2013
Sort ArrayList using Comparable in Java
Tags
# Core Java
# Java Collection
About Unknown
Kumar Bhatia is a technical resource working with Accenture and owns this blog on Java.
Java Collection
Labels:
Core Java,
Java Collection
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment