It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet add() method override Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashSet add() method override" Watch "HashSet add() method override" New topic
Author

HashSet add() method override

Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 423
Hi, Why can't I do this? Error is in the comments.


OCPJP 6.0-81% | Preparing for OCWCD
http://www.certpal.com/blogs/cert-articles | http://sites.google.com/site/mostlyjava/scwcd |
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 20147
    
  46

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6662
    
    5

add(E) is different from add(Object)


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Matt Swaggi
Ranch Hand

Joined: May 29, 2008
Posts: 61
Replace the Object with the Person .
It wil compile .
Prashant Shiralkar
Greenhorn

Joined: Apr 13, 2010
Posts: 19
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

Joined: Sep 20, 2010
Posts: 4087
    
  18

Yes.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Sunny Bhandari
Ranch Hand

Joined: Dec 06, 2010
Posts: 448

As stated above, the problem is related to Generics and not collections.

Have a look at Hashset's add method:


Use the following code:



Java Experience
Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 294


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



SQL Query Interview Question
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9435
    
  20

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


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashSet add() method override
 
jQuery in Action, 3rd edition