rubixibuc
rubixibuc

Reputation: 7397

Java and Generic Classes

What does this work without a type?

ArrayList l = new ArrayList();

Does it just default to type object if you don't specify a type, and that cast everything to object?

And what does it mean in the api when it says ClassType (won't display) a question mark within less than greater than signs.

Upvotes: 2

Views: 912

Answers (4)

aioobe
aioobe

Reputation: 421010

Does it just default to type object if you don't specify a type, and that cast everything to object?

Yes. That's almost* right.

A generic type (such as ArrayList) which is not provided with type parameters is called a raw type. Raw types are covered in the official trail Type Erasure:

For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime.

[...]

Type erasure exists so that new code may continue to interface with legacy code. Using a raw type for any other reason is considered bad programming practice and should be avoided whenever possible.

*) You can put any Object into an ArrayList, but as @newacct points out in the comments, ArrayList is not to be considered the same as ArrayList<Object>, since ArrayList (and ArrayList<?> btw) are both supertypes of ArrayList<WhatEver>, while ArrayList<Object> is not.

Upvotes: 2

uthomas
uthomas

Reputation: 754

You'll find a zip file in the root of the directory where you installed your JDK. In there, there is an src.zip.

I use eclipse as an IDE. In that you can attach the source so when you push CTRL+SHIFT+T and type ArrayList you'll be able to see it's source yourself ;) Actually it is also a good way to see how more expert ppl write source-code :)

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

Yes.

This is how Java used to work before generics were introduced. And in fact, this is still how it works, under the hood. The compiler performs basic type-checking, and then performs type erasure, so the bytecode that you're left with will be identical to that of the above.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500595

That's called a raw type. Avoid raw types where possible, as they reduce type safety.

Basically they're there for backward compatibility, so that when generics were introduced, existing code still compiled. As ever, see the Java Generics FAQ for more details.

Note that using a raw type is not the same as using a type with a type argument of Object, as raw types have all traces of generics removed from their effective API - even generic methods using other type parameters. That's part of what makes them dangerous.

Upvotes: 7

Related Questions