• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics

 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>' ?
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21420
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic