2013년 10월 17일 목요일

Comparable vs Comparator in Java

class HDTV implements Comparable {
 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(Object obj) {
  if (!(obj instanceof HDTV)) {
   throw new ClassCastException("Invalid object");
  }
  int size = ((HDTV) obj).getSize();
 
  if (this.getSize() > size)
   return 1;
  else if (this.getSize() < size)
   return -1;
  else
   return 0;
 }
}
 
public class Main {
 public static void main(String[] args) {
  HDTV tv1 = new HDTV(55, "Samsung");
  HDTV tv2 = new HDTV(60, "Sony");
  if(tv1.compareTo(tv2)>0){
   System.out.println(tv1.getBrand() + " is better.");
  }else{
   System.out.println(tv2.getBrand() + " is better.");
  }
 }
}
//**********************************************************************
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;
 }
 
 public void setBrand(String brand) {
  this.brand = brand;
 }
}
 
class SizeComparator implements Comparator{
 
 @Override
 public int compare(Object o1, Object o2) {
  int tv1Size = ((HDTV)o1).getSize();        
        int tv2Size = ((HDTV)o2).getSize();
 
        if(tv1Size > tv2Size){
         return 1;
        }else if(tv1Size < tv2Size){
         return -1;
        }else{
         return 0;
        }
 }
 
}
public class Main {
 public static void main(String[] args) {
  HDTV tv1 = new HDTV(55, "Samsung");
  HDTV tv2 = new HDTV(60, "Sony");
  HDTV tv3 = new HDTV(42, "Panasonic");
 
  ArrayList<HDTV> al = new ArrayList<HDTV>();
  al.add(tv1);
  al.add(tv2);
  al.add(tv3);
 
  Collections.sort(al, new SizeComparator());
  for(HDTV a: al){
   System.out.println(a.getBrand());
  }
 }
}

댓글 없음:

댓글 쓰기