Leonardo Go

Comparable와 Comparator 인터페이스 오버라이딩(3) 본문

Programming/Java

Comparable와 Comparator 인터페이스 오버라이딩(3)

Leonardo Go 2011. 8. 31. 18:46


 

import java.util.*;

class Student implements Comparable{
 String name;
 int ban;
 int no;
 int kor;
 int eng;
 int math;
 public Student(String name, int ban, int no, int kor, int eng, int math) {
  super();
  this.name = name;
  this.ban = ban;
  this.no = no;
  this.kor = kor;
  this.eng = eng;
  this.math = math;
 }

 int getTotal() {
  return kor + eng + math;
 }

 float getAverage() {
  return (int) (((getTotal() / 3f) * 10 + 0.5) / 10f);
 }

 public String toString() {
  return name + "," + ban + "," + no + "," + eng + "," + math + ","
    + getTotal() + "," + getAverage();
 }

 @Override
 public int compareTo(Object o) {
  if(o instanceof Student)
  {
   Student tmp = (Student)o;

   return name.compareTo(tmp.name);
  }
  else
   return -1;


 }
}

public class Exercise11_6 {
 static int getGroupCount(TreeSet tset, int from, int to){
//Comparator()클래스에서 구현한 compare메소드를를 가지고 비교를 하기때문에
평균을 기준으로 비교를하여 갯수를 구할수있다.
//from에 다음과 같은 값을 넣으면 평균은 from과 to가 되므로 
// 그사이값의 갯수를 알수가 있다. 

  Student fromS = new Student("", 0, 0, from, from, from);
  Student toS = new Student("bb", 0, 0, to, to, to);
  
  return tset.subSet(fromS, toS).size();
 }
 public static void main(String[] args) {
  TreeSet set = new TreeSet(new Comparator(){
   public int compare(Object o1, Object o2){
    if(o1 instanceof Student && o2 instanceof Student)
    {
     Student s1 = (Student)o1;
     Student s2 = (Student)o2;

     return (int)(s1.getAverage()-s2.getAverage());
    }

    return -1;
   }
  }
);

  set.add(new Student("홍길동",2,1,100,100,100));
  set.add(new Student("남궁성",1,2,90,70,80));
  set.add(new Student("김자바",2,3,80,80,90));
  set.add(new Student("이자바",2,4,70,90,70));
  set.add(new Student("안자바",2,5,60,100,80));

  Iterator it = set.iterator();
  while(it.hasNext())
   System.out.println(it.next());

  System.out.println("[60~69] : " + getGroupCount(set, 60, 70));
  System.out.println("[70~79] : " + getGroupCount(set, 70, 80));
  System.out.println("[80~89] : " + getGroupCount(set, 80, 90));
  System.out.println("[90~100] : " + getGroupCount(set, 90, 101));
 }

}