wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "generics" Watch "generics" New topic
Author

generics

Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

HashMap<Integer, String> hm = new HashMap<Integer,String>();
Iterator<Map.Entry> a = hm.entrySet().iterator(); //compilation error

Why the raw type must be parametrized? I thought that generics is flexible to fit the legacy code.


SCJP6, SCWCD5, OCE:EJBD6.
BLOG: http://leakfromjavaheap.blogspot.com
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

This will work



Is your question, 'why cant I just say the iterator contains Map.Entry elements instead of telling the compiler it contains Map.Entry<Integer, String>' ?


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

You have mistaken. That works:
Iterator<Map.Entry<Integer, String>> iterator = hm.entrySet().iterator();

But why the type must be parametrized?

That runs well:
HashMap hm = new HashMap<Integer, String>();

So why must the first case be parametrized?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18543
    
  40

Why the raw type must be parametrized? I thought that generics is flexible to fit the legacy code.


Well, your two choices are...



This...



is just using Generics, but not correctly. Either you use generics or you don't -- using it partially is not allowed.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

So what about that:
HashMap hm = new HashMap<Integer, String>();
HashMap<Integer, String> hm = new HashMap();
Both run pretty well.


EDIT:
Well, I see. Your answer if for nested generics. OK, I understand!
Thanks!

EDIT2:
But one more thing:
List<List> list = new ArrayList<List>(); //runs well

Can you explain me that again?

EDIT3:
OK, I will explain it to myself:
List<List> list = new ArrayList<List<String>>(); //doesn't work
Everything is clear!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generics
 
Similar Threads
Generics
Generics -really very hard question
Why are Generics necessary here?
Iterator in Generics
Generics