-
How to sort an arraylist of objects?
about 8 years ago
-
about 8 years ago
class 1 => Person.java
public class Person implements Comparable {
private int age; private String name;
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public int compareTo(Person person) { // TODO Auto-generated method stub if(this.age == person.age) { return 0; } else if(this.age < person.age) { return -1; } else { return 1; } }
@Override public String toString() { return "name => " + this.name + ", age => " + this.age; }
}
class 2 => PersonTest.java
public class PersonTest {
public static void main(String[] args) { // TODO Auto-generated method stub
Person person1 = new Person(); person1.setAge(23); person1.setName("A");
Person person2 = new Person(); person2.setAge(19); person2.setName("B");
Person person3 = new Person(); person3.setAge(25); person3.setName("C");
Person person4 = new Person(); person4.setAge(22); person4.setName("D");
Person person5 = new Person(); person5.setAge(23); person5.setName("E");
List persons = new ArrayList<>(); persons.add(person1); persons.add(person2); persons.add(person3); persons.add(person4); persons.add(person5);
System.out.println("before sorting => " + persons.toString());
Collections.sort(persons);
System.out.println("after sorting => " + persons.toString());
}
}
-
about 8 years ago
if you want to sort an arraylist of some objects then Simply implement that Class with comparable interface and override compareto() method. Inside compareto() you can do logic according to your logic.
-
about 8 years ago
@rishi02071990@gmail.com
Thank you. But it would be better if you could explain with the help of an example.
-
-
about 8 years ago
@sri.bharath72@gmail.com
Thank you.
-
4 Answer(s)