Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Ashan Kaya   on Jan 24 In Java Category.

  
Question Answered By: Burk Martin   on Jan 24

Here is an example  using the Comparable interface.
Let say, you have MyObject which consists of 'key' and 'value',
and you want to sort it by the 'value';

=====================================================
import java.util.*;

public class  Test {
public Test(String[] args) throws  Exception {
MyObject[] o = {new MyObject("ADF", "SKAK"),
new MyObject("S", "DJD"),
new MyObject("ADF", "DJD"),
new MyObject("XDJD", "ZSKSK"),
new MyObject("ZDS", "XSSS")};
List l = Arrays.asList(o);
System.out.println(l + "\n");
Collections.sort(l);
System.out.println(l);
}

public static  void main(String[] args) {
try {
new Test(args);
} catch (Exception e) {
e.printStackTrace();
}
}

private class MyObject implements Comparable {
private String key;
private String value;

public MyObject(String key, String value) {
this.key = key;
this.value = value;
}

public boolean equals(Object o) {
if (o instanceof MyObject) {
MyObject mo = (MyObject) o;
return this.key.equals(mo.key) && this.value.equals(mo.value);
} else {
return false;
}
}

public String toString() {
return key + " " + value;
}

public int  compareTo(Object o) {
MyObject mo = (MyObject) o;
int x = value.compareTo(mo.value);
// if value is equal, then sort the key
return (x != 0) ? x : key.compareTo(mo.key);
}
}
}

I hope this is what you are looking for.

Share: 

 

This Question has 1 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on compareTo explanation Or get search suggestion and latest updates.


Tagged: