Java error: Comparison method violates its general contract

前端 未结 10 2152
别跟我提以往
别跟我提以往 2020-11-22 04:17

I saw many questions about this, and tried to solve the problem, but after one hour of googling and a lots of trial & error, I still can\'t fix it. I hope some of you ca

10条回答
  •  悲哀的现实
    2020-11-22 05:13

            if (card1.getRarity() < card2.getRarity()) {
                return 1;
    

    However, if card2.getRarity() is less than card1.getRarity() you might not return -1.

    You similarly miss other cases. I would do this, you can change around depending on your intent:

    public int compareTo(Object o) {    
        if(this == o){
            return 0;
        }
    
        CollectionItem item = (CollectionItem) o;
    
        Card card1 = CardCache.getInstance().getCard(cardId);
        Card card2 = CardCache.getInstance().getCard(item.getCardId());
        int comp=card1.getSet() - card2.getSet();
        if (comp!=0){
            return comp;
        }
        comp=card1.getRarity() - card2.getRarity();
        if (comp!=0){
            return comp;
        }
        comp=card1.getSet() - card2.getSet();
        if (comp!=0){
            return comp;
        }   
        comp=card1.getId() - card2.getId();
        if (comp!=0){
            return comp;
        }   
        comp=card1.getCardType() - card2.getCardType();
    
        return comp;
    
        }
    }
    

提交回复
热议问题