This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method with Generic Argument 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 "Method with Generic Argument" Watch "Method with Generic Argument" New topic

Method with Generic Argument

Sudharsan Ashwin

Joined: Mar 09, 2010
Posts: 18

Can anyone explain..How is it that passthebuck(listall) is compiling fine? Though in the method definiton it is mentioned as List<String> ?
Just tried a sample program
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774

It is because mixing of legacy and non-legacy code is allowed. Why do you think such method should work

In order to avoid breaking the legacy code because of generics, the mixing of legacy and non-legacy can be combined.
Did your program give any warnings?

Hope this helps,

My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
Ulrich Vormbrock
Ranch Hand

Joined: Apr 15, 2010
Posts: 73
Hi Sudharsan,

it's right, you are mixing legacy- with non-legacy code.
Besides, it's up to you to make sure that later, you prevent operations such as "assigning a String to an int", etc.

At runtime, type-erasure comes into play, as you can simply verify decompiling (with cavaj) your class file:

As you can see, the generic in line 22 (<String>) has disappeared!

When I try to compile your class file with "-Xlint" (for example within the vi-Editor), I get the following output:

$ javac -Xlint warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List listall.add(new String("Hi"));
^ warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List listall.add(45);
^ warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List listall.add(56.90);
^ warning: [unchecked] unchecked conversion
found : java.util.List
required: java.util.List<java.lang.String>
4 warnings

Hope this helps!

SCJP 6 (88%), SCWCD (89%)
Have you checked out Aspose?
subject: Method with Generic Argument
It's not a secret anymore!