관리 메뉴

HAMA 블로그

Java ArrayList 객체 정렬 본문

Java

Java ArrayList 객체 정렬

[하마] 이승현 (wowlsh93@gmail.com) 2015. 5. 14. 15:24

1. 정렬하고자 하는 객체에  Comparable 인터페이스를 구현한다.

2. Collections.sort 함수로 정렬한다.



public class SwitchInfo  implements Comparable<SwitchInfo> {


private int id;

private double   power;

public SwitchInfo(int id ){

this.id = id;

}


public double getPower() {

return power;

}


public void setPower(double power) {

this.power = power;

}


@Override

public int compareTo(SwitchInfo si) {

if (this.power >  si.power) {   // 내림차순 , 오름차순으로 하려면 < 으로~

return -1;

} else if (this.power == si.power) {

return 0;

} else {

return 1;

}

}

}



ArrayList<SwitchInfo> switches =  group.getSwitches();


Collections.sort(switches);  // Power 를 내림차순으로  정렬

Comments