开发者

Java and Generic Classes

开发者 https://www.devze.com 2023-02-22 12:15 出处:网络
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开发者_如何学Go to object?

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开发者_如何学Go 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.


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.


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.


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.


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消