mutable fields for objects in a Java Set

后端 未结 4 1797
悲&欢浪女
悲&欢浪女 2020-12-16 18:18

Am I correct in assuming that if you have an object that is contained inside a Java Set<> (or as a key in a Map<> for that matter), any fields that are used to determi

4条回答
  •  一个人的身影
    2020-12-16 18:33

    Yes, that will cause bad things to happen.

    // Given that the Toy class has a mutable field called 'name' which is used
    // in equals() and hashCode():
    Set toys = new HashSet();
    Toy toy = new Toy("Fire engine", ToyType.WHEELED_VEHICLE, Color.RED);
    toys.add(toy);
    System.out.println(toys.contains(toy)); // true
    toy.setName("Fast truck");
    System.out.println(toys.contains(toy)); // false
    

提交回复
热议问题