Re: Generics references
- From: dagon@xxxxxxxxx (Mark Rafn)
- Date: Tue, 29 May 2007 09:10:20 -0700
jupiter <jupiter49byebyeSpam@xxxxxxx> wrote:
I've noticed that the type in generic declarations is not
"inherited" by new references to the object. This seems
inconsistent to me but maybe there's a good reason for it.
Type inference is intentionally weaker than it could be. There are good
reasons for it, I suspect, but it annoys me sometimes.
To wit:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList list2 = list;
List2 is explicitly NOT declared as a parameterized type. It happens to have
an ArrayList<String> in it now, but you could assign it an ArrayList<Object>
later without error.
list1.add(new Integer(3)); //compiler catches it as expected.
list2.add(new Integer(3)); //compiler is fat, dumb and happy.
Right, because you told it to be.
I thought the idea of a reference was to point to the original
object and pick up all of the relevant data. Why not type?
Type is tricky. It's both a property of the variable and a property of the
referent. The object type can be more specific than the variable, and that's
how polymorphism works.
Note the similarity to:
LinkedList list1 = new LinkedList();
List list2 = list1;
list1.addFirst("first"); // allowed, addFirst is a method on LinkedList
list2.addFirst("first"); // disallowed, addFirst is NOT on the List interface
--
Mark Rafn dagon@xxxxxxxxx <http://www.dagon.net/>
.
- Follow-Ups:
- Re: Generics references
- From: jupiter
- Re: Generics references
- References:
- Generics references
- From: jupiter
- Generics references
- Prev by Date: Re: Which are the "must own" Java books?
- Next by Date: Re: Collections.class methods anachronisms?
- Previous by thread: Generics references
- Next by thread: Re: Generics references
- Index(es):
Relevant Pages
|
|