2016년 7월 7일 목요일

안드로이드에서 객체 정렬(sort) 하기





안드로이드에서 객체 정렬(sort) 하기

Arrays.sort() 메소드를 이용하면 배열 안의 원소들을 정렬할수 있다.
그러나 객체가 배열의 원소일때는 이 메소드로는 처리가 안된다.
정렬 대상이 객체(클래스의 객체)일 경우는 Comparable이라는 인터페이스를 통해서 가능하다.

이름(name)과 나이(age)라는 2개의 필드를 가진 People라는 클래스가 있다고 가정해 보자.
이 클래스를 정렬할려면 Comparable라는 인터페이스를 통해서 어떻게 구현하는지 살펴본다.

public class People implements Comparable<People>{
private String name;
private int age;
public People(String _name, int _age){
this.name = _name;
this.age = _age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public int compareTo(People _people){
//여긴 이름을 기준으로 정렬
//이건 내림 차순
//문자열은 이런 식으로 가능
// return this.name.compareTo(_people.name); 
//이건 오름차순
//문자열은 이런 식으로 가능
// return _people.name.compareTo(this.name);
//여기서부터는 나이를 기준으로 정렬
//이건 내림 차순
//숫자는 위의 compareTo()로 안되고 다음과 같이 처리 해야됨
if (this.age < _people.age){
// return -1; //이렇게 하면 내림 차순
return 1; //이렇게 하면 오름 차순
} else if (this.age == _people.age){
return 0;
} else {
// return 1; //이렇게 하면 내림 차순
return -1; //이렇게 하면 오름 차순
}
}
}

People이라는 객체를 사용하는 곳은 다음과 같다.
보통 Listview의 각 항목들을 보여줄때 이름을 기준으로나 혹은 나이를 기준으로 내림차순 혹은 오름 차순으로 보여주고자 할때 Comparable 인터페이스를 활용하면 간단히 처리할 수 있다.
여기서는 단지 화면의 TextView에 보여주는 기능을 구현해본다.

public class ExObjectSortActivity extends Activity {
private TextView txt;
private ArrayList<People> arrList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ex_object_sort);
txt = (TextView)findViewById(R.id.txt);
arrList = new ArrayList<People>();
arrList.add(new People("홍길동", 15));
arrList.add(new People("고길동", 25));
arrList.add(new People("둘리", 12));
arrList.add(new People("챨리", 32));
arrList.add(new People("강감찬", 120));
String rt = "";
String str = "";
//기존 저장된 순서대로 출력
for(int i=0; i<arrList.size(); i++){
str += arrList.get(i).getName()+" - "+arrList.get(i).getAge()+"\n";
}
str += "\n\n\n";
//Comparable에서 지정된 대로(내림차순 혹은 오름차순) 정렬됨
Collections.sort(arrList);
//정렬된 결과를 출력하기
for(int i=0; i<arrList.size(); i++){
str += arrList.get(i).getName()+" - "+arrList.get(i).getAge()+"\n";
}
txt.setText(str);
}
}

ex_object_sort.xml 레이아웃은 다음과 같이 되어 있다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="20sp" />
</RelativeLayout>

댓글 없음:

댓글 쓰기