0

Possible Duplicate:
Sorting a collection of objects
Sorting an ArrayList of Contacts based on name?

A quick question for you:

I've got an ArrayList<MyObject> filled with MyObject objects. I would like them to be sorted based on an integer variable of MyObject.

Is there a ready way to implement this or will I have to write a quicksort/mergesort myself?

Thank you for your time, Dimitris

Community
  • 1
  • 1
Dimitris Sfounis
  • 2,312
  • 4
  • 30
  • 46

4 Answers4

2

You need to implement Comparable interface and override the compareTo. Following example I have assumed that there is a member variable 'name' on which you will be comparing the objects.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class MyObject implements Comparable<MyObject>{
private String name;
private int id;

public String getName() {
    return name;
}

public MyObject(String name, int id) {
    super();
    this.name = name;
    this.id = id;
}
@Override
public int compareTo(MyObject o) {
    return name.compareTo(o.getName());
}   
@Override
public String toString() {
    return name+"\t"+id+"\n";
}
}

         public class Test {
         public static void main(String[] args) {
            List<MyObject> list = new ArrayList<MyObject>();
     list.add(new MyObject("John", 10));
     list.add(new MyObject("Mark", 11));
     list.add(new MyObject("Steve", 9));
     Collections.sort(list);
     System.out.println("Sorted list is :"+list);
 }
 }
Vallabh Patade
  • 4,790
  • 5
  • 30
  • 40
1

You want to look at Comparators, they let you define the sort order whatever way you want. Here's the doc http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

Peter Wooster
  • 5,952
  • 1
  • 26
  • 39
1

You can use Array.sort(...) You must only implement a Comparator for your MyObject or make it Comparable.

Tomasz Nurkiewicz
  • 324,247
  • 67
  • 682
  • 662
MrSmith42
  • 9,535
  • 6
  • 36
  • 48
1

You can also use the Collections.sort() libraries and pass in your collections (ArrayList) and a specifically designed Comperator for your objects.

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html[enter link description here][1]
Afshin Moazami
  • 2,054
  • 5
  • 33
  • 55
Mechkov
  • 4,264
  • 1
  • 16
  • 25