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

2
  • ok post the structure of your 'myobject' Commented Jan 24, 2013 at 19:42
  • @Arpit It's a basic class MyObject{ private int num; /*constructor, setter and getter for num here*/ } , friend. Commented Jan 24, 2013 at 19:51

4 Answers 4

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);
 }
 }
Sign up to request clarification or add additional context in comments.

Comments

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]

1 Comment

Thank you, friend. It was as simple as I thought.
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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.