Why isn't Collections.binarySearch() working with this comparable?

前端 未结 2 1535
不思量自难忘°
不思量自难忘° 2021-01-27 01:00

I have this Player class which implements the Comparable interface. Then I have an ArrayList of Players. I\'m trying to use <

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 01:43

    As long as you are implementing Comparable, you can make compareTo() consistent with equals() by also overriding equals() and hashCode(). This is particularly easy in this case, as you can simply delegate to String. Moreover, it's convenient if you ever need a Map containing instances of Player:

    class Player implements Comparable {
    
        private String username;
        private String password;
    
        // ...
    
        @Override
        public int compareTo(String name) {
            return username.compareTo(name);
        }
    
        @Override
        public boolean equals(Object obj) {
            return obj instanceof Player
                && username.equals(((Player)obj).username);
        }
    
        @Override
        public int hashCode() {
            return username.hashCode();
        }
    }
    

提交回复
热议问题