简体   繁体   中英

Override toString method and avoid collision

I am wondering if I override toString method that returns one of the instance from the object then is it more likely to cause collision ? for example,

class Student{
   private String name;
   private double gpa;
   public Student(String name, double gpa){
      this.name = name;
      this.gpa = gpa;
   }
   public String toString(){
      return name;
   }
}

So the problem is that I want to show name when it prints the Student object, but when two different student with the same name (different gpa) will cause me an issue if I store them all in a HashMap. What are the alternatives to avoid collision without modifying or with minimal modification on the original Student class ?

Given your tags, you seem to talk about hash collision in HashMap?

toString() has nothing to do with the behaviour of HashMap. The only two important methods for objects that would be keys in a HashMap are equals(Object) and hashcode() .

Also, HashMap is collision-safe, so you don't need to care about hash collisions.

你应该重写和实现hashCodeequals ,如果你想使用你的类在基于哈希表集合一样的HashMap正确,HashSet的等toString无关与HashMap中。

Maybe this will help:

class Student{
    private static AtomicInteger nextUniqueID = new AtomicInteger (0);

    private final int uniqueID = nextUniqueID.getAndIncrement ();
    private String name;
    private double gpa;
    public Student(String name, double gpa){
        this.name = name;
        this.gpa = gpa;
    }
    public String toString(){
        return name + " [" + uniqueID + "]";
    }
}

The default implementation of hashCode in java is to mix all of its variables' values together and hash that. So, it doesn't matter what toString is.

HashMap is internally stored in a table. The key is used to identify the table index so it is important that the key class overrides hashCode() as the hashCode value will be used to determine the table index. If two different keys result in the same hash code or different hash codes map to the same table index, there will be a collision which means two different entries point to the same bucket location. If there is a collision, the previous entry will be linked to the new (key,value) thus a linked list starts.

If you want your student class to be used as key, its important that it overrides hashCode(). Try to make sure that hashCode() returns unique values to minimize collisions. If two students have same name, may be you should also rely on some id. In that case, both name and Id need to be used to calculate the hashCode. Also make sure you override equals(), this is important in case of collisions, key.equals() will help to identify your key in the linked list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM