How to save new objects into an arrayList?

How do you sort an Arraylist of objects in Java?

  • I have created an arraylist which stores objects. Each object consists of a name and age. How can I sort this arraylist in descending order of age?

  • Answer:

    Because of how ArrayLists behave, I would recommend a merge sort for this purpose. You can see the algorithm on Wikipedia. I could write the exact method if I knew the name and API of the class you're dealing with.

Maikol at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

Your Object has to implements Comparable which enforces the following contract public int compareTo( Object o ) throws ClassCastException { Person anotherPerson = (Person)o; return this.getAge() - anotherPerson.getAge(); } List<Person> persons = new ArrayList<Person>(); persons.add( new Person( "Billy Bob", 33 ) ); persons.add( new Person( "Squeeky Sue", 29) ); ... Collections.sort( persons ).reverse(); // to get your descending order. Note I use the interface List which implements Collections.

deonejuan

import java.util.*; Arrays.sort(objectArray, new Comperator<ABC>() { public int compare(ABC o1, ABC o2) { return o2.getAge() - o1.getAge(); } });

Voice of Insanity

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.