Even the first call to method map.put() will throw a ClassCastException. And more over ther is no method map.add() , i think you mean map.put() ?This will not help because it does not solve the basic problem of bad hashCode() method that exists with Book class. Moreover, if TreeMap is used, the second map.add() call will throw a ClassCastException because Book does not implement Comparable interface.
About Question enthuware.ocpjp.v7.2.1304 :
Moderator: admin
-
- Posts: 17
- Joined: Fri Oct 11, 2013 10:31 am
- Contact:
About Question enthuware.ocpjp.v7.2.1304 :
-
- Site Admin
- Posts: 10046
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1304 :
You are right. Even the first call throws ClassCastException now. With previous versions of Java, the first call did not require any comparison and so there was no need to cast it to Comparable.
If you like our products and services, please help us by posting your review here.
-
- Posts: 4
- Joined: Tue Dec 19, 2017 9:18 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1304 :
why
Book b = new Book("A111"); // in BookStore constructor
Book b = new Book("A111"); // in public static void main
has different hashCode?
Book b = new Book("A111"); // in BookStore constructor
Book b = new Book("A111"); // in public static void main
has different hashCode?
-
- Site Admin
- Posts: 10046
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1304 :
That's because the Book class doesn't implement the hashCode method. Therefore, the inherited version from the Object class is used. Object's hashCode returns a different value for a different object.
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 82 guests