开发者

What is the role of the data types inside of < > in Java? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Java Generics

To be mo开发者_开发百科re specific, whats the role of the <String> in the following line of code?

private List<String> item = new ArrayList<String>();


Mainly to allow the compiler to raise an error if you don't insert the right kind of data into the list or if you expect data of the wrong type from the list at the moment of extraction

But see the generics tutorial for an explanation: http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html


It means that the list can only contain items of the String type. It can't contain items of Number, SomeObject, WhateverType types.

It's called Generics. In Java, it's actuallty compile time syntactic sugar to make the code more robust without the risk for ClassCastException and consorts on retrieving the list items during runtime. You can find here a Sun tutorial on the subject, it also explains the reasoning behind the move to Generics.


Thats Generics - allowing the compiler to keep track of what is inside lists etc. Notoriously tricky in Java.

Here is an excellent description: http://www.infoq.com/resource/articles/bloch-effective-java-2e/en/resources/Bloch_Ch05.pdf


Those are generics and where introduced on the v1.5 of Java

They allows you to provide compile time check of the class being used.

You can read the declaration:

private List<String> item = new ArrayList<String>();

As:

 private List of Strings named item initialized with an ArraysList of Strings

So, if you attempt to put something that's not a String you'll get a compile time exception:

 private List<String> items = new ArrayList<String>();
 ... 
 items.add( new Date() ); // fails at compilation time

When you get something from that list you'll get a list

 private List<String> item = new ArrayList<String>();
 ...
 items.add( "Hello" );
 String s = items.get(0);// returns 

To use different classes you provide a different type:

 private List<Date> dates = new ArrayList<Date>();

And now you can only use Dates with that collection.


The reason for your this new Java Edition after JDK 1.5 or later as it gives more ease to the programmer as it allow type safety at compile type only. The million dollar question is why it is needed so? The answer is let say you have List in which you want to add integer type objects only into it like below

List list = new ArrayList();
list.add(new Integer(5));

but by mistake you add String object into it.

list.add("Test");

Now in you other code you are using this list assuming that all values are integer

(Integer)list.get(2);

this will give error at run time, so to avoid this it is better to defined your list at declaration part like list and it will not allow you to add string object to you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜