2016-04-01 30 views
1

aşağıda hatası alıyorum kontrol ettikten sonra genel sözleşme ihlalKarşılaştırma yöntemi bile boş

aktivitesini devam ettirmek için açılamıyor {com.xxx.yyy.zzz.HomeActivity} : java.lang.IllegalArgumentException: Karşılaştırma yöntemi, ihlal genel sözleşme!

Dize için boş durumları ele alıyorum bile bu hata geliyor. Neyin yanlış olabileceğine dair ipuçları.

public class ConversationComparer implements Comparator<Conversation> { 
@Override 
public int compare(Conversation x, Conversation y) { 

    if (x.getLastMessageDate() == null) { 
     return 1; 
    } 

    if (y.getLastMessageDate() == null) { 
     return -1; 
    } 

    return y.getLastMessageDate().compareTo(x.getLastMessageDate()); 

}} 


public java.util.Date getLastMessageDate() { 
     return lastMessageDate; 
    } 

altına Kod Bu i karşılaştırıcı

if (conversationListAdapter != null) { 
      Collections.sort(this.list,new ConversationComparer()); 
      conversationListAdapter.notifyDataSetChanged(); 
     } 

cevap

1

Ben x.getLastMessageDate() ve y.getLastMessageDate() hem null nerede doğru olaya el kalmamasıdır ile bu yanlış görebilirsiniz tek şey nasıl kullanılacağı.

Bu satırı yöntemin başına eklerseniz, sözleşmeyi karşılar.

if (x.getLastMessageDate() == null && y.getLastMessageDate() == null) 
    return 0; 
2

Ayrıca, her ikisi de boşsa, x ve y'yi tekrar işaretlemeniz ve 0 değerini döndürmeniz gerekir.

@Override 
public int compare(Conversation x, Conversation y) { 

    if (x == y || (x != null && y != null && x.getLastMessageDate() == y.getLastMessageDate())) 
     return 0;  

    if (x == null) 
     return 1; 

    if (y == null) 
     return -1; 

    if (x.getLastMessageDate() == null) 
     return 1; 

    if (y.getLastMessageDate() == null) 
     return -1; 

    return y.getLastMessageDate().compareTo(x.getLastMessageDate()); 
} 

Ayrıca, hangi verilerin türü "getLastMessageDate()" döner bilmek ilginç olurdu.

+0

getlastmessage is java.util.Date – ila

+0

Bu antisimetrik değildir. X == null' ve 'y.getLastMessageDate() == null' olduğunu varsayalım. Daha sonra karşılaştırın (x, y) == 1' ve '((x, y) == 1'i karşılaştırın. –

+0

Bu durumda istisnanın compareTo yönteminden geldiğini düşünmüyorum. Date.compareTo, InvalidArgumentException vermiyor. Belki tüm yığın izini sağlarsınız. – Till

İlgili konular