Asaf Nevo
Asaf Nevo

Reputation: 11678

android sorting an array

i'm trying to sort my array but from some reason i got the following error in my compareTo function:

Cannot invoke compareTo(int) on the primitive type int

my code:

private void sortFriendList()
{
    Arrays.sort(friendsList, new Comparator<FacebookUser>() {

        @Override
        public int compare(FacebookUser lhs, FacebookUser rhs) {                
            ChatMessage[] firstChatMessages = app.getDatabaseManager().getChatMessages(lhs.getId());
            ChatMessage[] lastChatMessages = app.getDatabaseManager().getChatMessages(rhs.getId());
            int firstLastMessageTime = (int) firstChatMessages[firstChatMessages.length-1].getTime();
            int lastLastMessageTime = (int) lastChatMessages[firstChatMessages.length-1].getTime();
            return firstLastMessageTime.compareTo(lastLastMessageTime);
        }
    });     
 }

the code supposed to sort an array buy time stored in long type (which i've cast to int)

Upvotes: 0

Views: 321

Answers (4)

keiki
keiki

Reputation: 3459

The compareTomethod only works on objects. An primitive int is no object. You have to manually compare the int values and return either negative, zero or positive value, if this values is less, equal or greater than the other value.

Using the Integer wrapper class for that is just wasting resources.

This morning I'm more willing to provide some code:

long firstLastMessageTime = ...
long lastLastMessageTime = ...
if (firstLastMessageTime < lastLastMessageTime) {
    return -1;
}
if (firstLastMessageTime > lastLastMessageTime) {
    return 1;
}
return 0;

In some cases you could do firstLastMessageTime minus lastLastMessageTime, but that maybe lead to errors if you handle with negative values or if the difference can be bigger than a 32bit int value. So to be 100% sure, just use the above method all the time.


Additional comment:

Is the value really a int value? Usually the time is defined as the milliseconds since 1.1.1970 in Java, which as datatype is long.

Upvotes: 3

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Don't cast long to int to avoid loss of precision. Rather box it to Long

long firstLastMessageTime = //...
long lastLastMessageTime = //...
return Long.valueOf(firstLastMessageTime).compareTo(Long.valueOf(lastLastMessageTime));

Upvotes: 2

greenkode
greenkode

Reputation: 3996

You Cannot invoke compareTo on primitive types, You should use their wrapper classes. Integer rather than int

Upvotes: 0

Vinay Lodha
Vinay Lodha

Reputation: 2223

Try something like this

        return Integer.valueof(firstLastMessageTime).compareTo(lastLastMessageTime);

Before invoking comapreTo method you have to wrap int into Integer object.

Upvotes: 2

Related Questions