소프트웨어 개발/Java - Basic

간단한 객체가 들어있는 어레이리스트 정렬 후 바이너리 서치

늘근이 2016. 10. 10. 22:26


package etc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class BinarySearchClassTest {

    public static void main(String[] args) {
        ArrayList<Car> list = new ArrayList<Car>();
        list.add(new Car(1000, "hi"));
        list.add(new Car(12350, "hi"));
        list.add(new Car(123400, "hi"));
        list.add(new Car(11100, "hi"));
        list.add(new Car(500, "hi"));
        list.add(new Car(130, "hi"));

        Collections.sort(list, new Com());

        int index = Collections.binarySearch(list, new Car(500, "aa"), new Com());

        System.out.println(list.toString());

        System.out.println("index : " + index);
        System.out.println(list.get(index));

    }

}

class Com implements Comparator<Car> {

    @Override
    public int compare(Car o1, Car o2) {
        // TODO Auto-generated method stub
        return o1.price - o2.price;
    }

}

class Car {
    int price;
    String name;

    public Car(int price, String name) {
        super();
        this.price = price;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Car [price=" + price + ", name=" + name + "] \n";
    }

}