look directly at the code, why I directly add a String object contains () returns true, when adding a Dog object, it returns false, and Set is not able to add a repeating element, why can I add two Dog objects and not String objects
class Dog {
String color;
public Dog(String s){
color = s;
}
}
public class SetAndHashCode {
public static void main(String[] args) {
HashSet<Dog> dogSet = new HashSet<Dog>();
boolean resultq;
dogSet.add(new Dog("we have white"));
System.out.println("We have " + dogSet.size() + " white dogs!");
resultq = dogSet.contains(new Dog("we have white"));
System.out.println(resultq);
HashSet<String> books = new HashSet<String>();
//
books.add(new String("Struts2"));
books.add(new String("Struts2"));
boolean result = books.contains(new String("Struts2"));
System.out.println("We have " + books.size() + " books!");
System.out.println(result);
//
System.out.println(books);
}
}
the result of execution is
* * We have 2 white Dogs!
false
We have 1 books!
true
[Struts2 authoritative Guide] * *