The Comparable
interface (in java.lang
package) is used to order the objects of user-defined class. It has compareTo(Object)
method, which is used to sort objects based on a specific attribute declared in the user-defined class.
The following example shows, how this interface is used.
Source code of Item.java
package com.t4b.test;
public class Item implements Comparable<Item> {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
@Override
public int compareTo(Item o) {
if (id == o.id)
return 0;
else if (id > o.id)
return 1;
else
return -1;
}
}
Source code of TestMain.java
package com.t4b.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class TestMain {
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList<Item>();
items.add(new Item("Apple", 1, 150.0));
items.add(new Item("Bag", 3, 1050.0));
items.add(new Item("Grape", 2, 250.0));
Collections.sort(items);
Iterator<Item> itr = items.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.