[JAVA][Comparator 예제]
the space coding
Comparator 예제
1 2 3 4 5 6 7 8 9 10 11 12 |
package exam04;
public class Fruit { public String name; public int price;
public Fruit(String name, int price) { this.name = name; this.price = price; }
} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package exam04;
import java.util.Comparator;
public class DescendingComparator implements Comparator<Fruit> {
@Override public int compare(Fruit arg0, Fruit arg1) { // TODO Auto-generated method stub if(arg0.price < arg1.price) return 1; // 오름차순 정렬 else if(arg0.price == arg1.price)return 0; else return -1; }
} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package exam04;
import java.util.Iterator; import java.util.TreeSet;
public class ComparatorExample {
public static void main(String[] args) { TreeSet<Fruit> treeSet = new TreeSet<Fruit>(new DescendingComparator());
treeSet.add(new Fruit("포도",3000)); treeSet.add(new Fruit("수박",10000)); treeSet.add(new Fruit("딸기",6000));
Iterator<Fruit> iterator = treeSet.iterator(); while(iterator.hasNext()) { Fruit fruit = iterator.next(); System.out.println(fruit.name+""+fruit.price); }
}
} |