Android

[오브젝트 캐스팅오류 처리]UncaughtException: java.lang.ClassCastException: com.app.test.database.NumberTogetherCountVo cannot be cast to java.lang.Comparable at java.util.Collections$ReverseComparator.compare(Collections.java:5165)

벨류오브젝트객체를 담은 어레이리스트의 데이터를 정렬하는 과정에서 발생한 오류이다. ArrayList를 내림차순으로 정렬하기 위해 Collections클래스의 sort메서드를 사용하였다. 하지만 뜻밖에 오류가 발생하였다.

    java.lang.ClassCastException: com.app.test.database.NumberTogetherCountVo cannot be cast to java.lang.Comparable
        at java.util.Collections$ReverseComparator.compare(Collections.java:5165)
        at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
        at java.util.TimSort.sort(TimSort.java:234)
        at java.util.Arrays.sort(Arrays.java:1492)
        at java.util.ArrayList.sort(ArrayList.java:1470)
        at java.util.Collections.sort(Collections.java:206)
        at com.app.test.NumberActivity$testTask.onPostExecute(NumberActivity.java:989)
        at com.app.test.NumberActivity$testTask.onPostExecute(NumberActivity.java:814)
        at android.os.AsyncTask.finish(AsyncTask.java:771)
        at android.os.AsyncTask.access$900(AsyncTask.java:199)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-01-22 22:43:45.422 25287-25287/com.app.test E/UncaughtException: java.lang.ClassCastException: com.app.test.database.NumberTogetherCountVo cannot be cast to java.lang.Comparable
        at java.util.Collections$ReverseComparator.compare(Collections.java:5165)
        at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
        at java.util.TimSort.sort(TimSort.java:234)
        at java.util.Arrays.sort(Arrays.java:1492)
        at java.util.ArrayList.sort(ArrayList.java:1470)
        at java.util.Collections.sort(Collections.java:206)
        at com.app.test.NumberActivity$testTask.onPostExecute(NumberActivity.java:989)
        at com.app.test.NumberActivity$testTask.onPostExecute(NumberActivity.java:814)
        at android.os.AsyncTask.finish(AsyncTask.java:771)
        at android.os.AsyncTask.access$900(AsyncTask.java:199)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-01-22 22:43:45.881 25287-25588/com.app.test E/FirebaseCrash: Unable to parse Json response string to get message: No value for crashes

 

오류가 발생한 코드

private ArrayList<NumberTogetherCountVo> itemList = new ArrayList<NumberTogetherCountVo>();
...........생략
Collections.sort(itemList, Collections.reverseOrder());

오류가 발생한 이유는 데이터를 담고 있는 NumberTogetherCountVo객체에 여러개의 멤버변수들이 존재한다. Collections클래스의 sort()메서드는 NumberTogetherCountVo객체에서 어느 멤버변수를 기준으로 정렬을 해야하는지 기준이 없기때문에 발생한다.

 

오류 해결방법

NumberTogetherCountVo오브젝트에 Comparator 인터페스를 할당받아  compare()메서드를 오버라이드처리해주고 정렬대상의 칼럼에 대한 계산식을 추가해준다. 오름차순과 내림차순이 가능하도록 2개의 메서드를 구현하였다.

    public static Comparator<NumberTogetherCountVo> TogetherShowCountASC = new Comparator<NumberTogetherCountVo>() {
        @Override
        public int compare(NumberTogetherCountVo o1, NumberTogetherCountVo o2) {
            return o1.getNumCount() - o2.getNumCount();
        }
    };

    public static Comparator<NumberTogetherCountVo> TogetherShowCountDESC = new Comparator<NumberTogetherCountVo>() {
        @Override
        public int compare(NumberTogetherCountVo o1, NumberTogetherCountVo o2) {
            return o2.getNumCount() - o1.getNumCount();
        }
    };

 

NumberTogetherCountVo.java 전체코드

import java.util.Comparator;

public class NumberTogetherCountVo {
    int num;
    int num2;
    int numCount;
    String percenTage;

    public NumberTogetherCountVo(int _num, int _num2, int _numCount, String _percenTage){
        this.num = _num;
        this.num2 = _num2;
        this.numCount = _numCount;
        this.percenTage = _percenTage;
    }

    public int getNum2() {
        return num2;
    }

    public void setNum2(int num2) {
        this.num2 = num2;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public int getNumCount() {
        return numCount;
    }

    public void setNumCount(int numCount) {
        this.numCount = numCount;
    }

    public String getPercenTage() {
        return percenTage;
    }

    public void setPercenTage(String percenTage) {
        this.percenTage = percenTage;
    }
	
    //오름차순
    public static Comparator<NumberTogetherCountVo> TogetherShowCountASC = new Comparator<NumberTogetherCountVo>() {
        @Override
        public int compare(NumberTogetherCountVo o1, NumberTogetherCountVo o2) {
            return o1.getNumCount() - o2.getNumCount();
        }
    };

	//내림차순
    public static Comparator<NumberTogetherCountVo> TogetherShowCountDESC = new Comparator<NumberTogetherCountVo>() {
        @Override
        public int compare(NumberTogetherCountVo o1, NumberTogetherCountVo o2) {
            return o2.getNumCount() - o1.getNumCount();
        }
    };

}

 

구현한 코드를 호출하는 방법

Collections.sort(itemList, NumberTogetherCountVo.TogetherShowCountDESC);

 

[REFERNECE]

playground.naragara.com/507

 

[Java] 자바 배열 정렬 예제 : 오름차순, 내림차순, Arrays.sort(), Collections.reverseOrder()

배열의 값을 정렬하는 방법은 간단한다. 별도로 내가 코딩하지 않아도 한 번의 메소드 호출로 간편하게 정렬할 수 있다.Arrays클래스를 사용하면 된다. ■오름차순 정렬 Arrays.sort()메소드를 사용

playground.naragara.com

stackoverflow.com/questions/22314009/how-to-sort-arraylist-using-comparator

 

How to sort ArrayList using Comparator?

I have a Class Student that Implements a static method public static Comparator getCompByName() that returns a new comparator object for Student that compares 2 Students objects …

stackoverflow.com

beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/

 

Java ArrayList of Object Sort Example (Comparable And Comparator)

In this tutorial we will see how to sort an ArrayList of Objects by property using comparable and comparator interface. If you are looking for sorting a

beginnersbook.com

 

Leave a Reply

error: Content is protected !!