• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet add() method override

 
Harikrishna Gorrepati
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Why can't I do this? Error is in the comments.
 
Henry Wong
author
Marshal
Pie
Posts: 21008
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harikrishna Gorrepati wrote:Hi, Why can't I do this? Error is in the comments.



It is not an override, because the super class add method takes an E instance as it's it parameter -- and in your example, it takes a Person object. So, technically, it should be a overload, one for Person and one for Object.

Unfortunately, it can't be an overload either. Because of type erasure, both methods come out to the same signature.

So.... hence, a compile error.

Henry
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
add(E) is different from add(Object)
 
Matt Swaggi
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Replace the Object with the Person .
It wil compile .
 
Prashant Shiralkar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote: Because of type erasure, both methods come out to the same signature.

Here, do you imply: add(E e) and add(Object o)? If so, does that mean, after "type erasure", add(E e) of HashSet<E> looks like add(Object o)?
 
Stephan van Hulst
Bartender
Pie
Posts: 5590
55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
 
Sunny Bhandari
Ranch Hand
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As stated above, the problem is related to Generics and not collections.

Have a look at Hashset's add method:


Use the following code:

 
Javin Paul
Ranch Hand
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It will work with replacing Person with Object as well like below.

 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Javin Paul wrote:It will work with replacing Person with Object as well like below.

Your code will work but logically, if a class needs to extend a specific type of HashSet, then the code should be
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic