Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created July 15, 2014 03:25
Show Gist options
  • Select an option

  • Save adohe-zz/1e4f4a43bf1a7c63ec1b to your computer and use it in GitHub Desktop.

Select an option

Save adohe-zz/1e4f4a43bf1a7c63ec1b to your computer and use it in GitHub Desktop.
The difference between comparable and comparator....
package com.westudio.java;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class HDTV implements Comparable<HDTV> {
private int size;
private String brand;
public HDTV(int size, String brand) {
this.size = size;
this.brand = brand;
}
int getSize() {
return size;
}
void setSize(int size) {
this.size = size;
}
String getBrand() {
return brand;
}
void setBrand(String brand) {
this.brand = brand;
}
@Override
public int compareTo(HDTV o) {
if (this.size > o.size) {
return 1;
} else if (this.size < o.size) {
return -1;
}
return 0;
}
}
class Computer {
private int price;
private String brand;
public Computer(int price, String brand) {
this.price = price;
this.brand = brand;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
String getBrand() {
return brand;
}
void setBrand(String brand) {
this.brand = brand;
}
}
class PriceComparator implements Comparator<Computer> {
@Override
public int compare(Computer c1, Computer c2) {
int priceOne = c1.getPrice();
int priceTwo = c2.getPrice();
if (priceOne > priceTwo) {
return 1;
} else if (priceOne < priceTwo) {
return -1;
}
return 0;
}
}
public class Compare {
public static void main(String[] args) {
HDTV tvOne = new HDTV(55, "Samsung");
HDTV tvTwo = new HDTV(58, "Sony");
if (tvOne.compareTo(tvTwo) > 0) {
System.out.println("Samsung is better");
} else {
System.out.println("Sony is better");
}
Computer c1 = new Computer(6000, "Sony");
Computer c2 = new Computer(7000, "Lenovo");
Computer c3 = new Computer(8000, "Apple");
ArrayList<Computer> list = new ArrayList<Computer>();
list.add(c1);
list.add(c2);
list.add(c3);
Collections.sort(list, new PriceComparator());
for (Computer c : list) {
System.out.println(c.getBrand());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment