Professional Documents
Culture Documents
Collections are the different classes which are present in java.util package.
The collections classes are set of objects. There are several collection
classes
ArrayList
Vector
HashMap
HashTable
List
Stack
Queue and many more. Every Collection class is a set of objects. What
happens when we actually try to compare two objects? Every object will
have a unique code reference called as hash code. If We try to compare
two objects by equals() in general it actually compares the hash code but
not the data.
In order to compare the data we go for comparable and comparator
interfaces.
Comparable:
Comparable is used to compare two objects, and that class should
implement this comparable interface. We need to define the compareTo()
method to compare that objects.
class HDTV implements Comparable<HDTV> {
private int size;
private String brand;
public HDTV(int size, String brand) {
this.size = size;
this.brand = brand;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public int compareTo(HDTV tv) {
if (tv1.compareTo(tv2) > 0) {
System.out.println(tv1.getBrand() + " is better.");
} else {
System.out.println(tv2.getBrand() + " is better.");
}
Comparator:
If we want to compare two objects based on certain attributes then we go for this
comparator interface. For this we need to implement these comparator interface to that
class.
We need to define the compare() method in that class to compare the two objects.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class HDTV {
private int size;
private String brand;
public HDTV(int size, String brand) {
this.size = size;
this.brand = brand;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getBrand() {
return brand;
}
main(String[] args) {
new HDTV(55, "Samsung");
new HDTV(60, "Sony");
new HDTV(42, "Panasonic");