Why we use like this?

HiIn a sample coding of tutorial i saw the following lines. There what is the purpose of <String>?Can anybody explain me ?List<String> list = new ArrayList<String>(c);Thanks you so much.
[272 byte] By [myque-ans@soona] at [2007-11-27 0:47:45]
# 1

that's called generics, a new feature in java 1.5. used to be available as a library called Pizza. it gives us added compile-time type safety

basically, before they were introduced, Collections would always return java.lang.Object references, and you had to cast the returned value to the correct type. with generics, you can avoid all that. in your posted example, the list can be reasonably trusted to contain Strings, and get(int) will return a String, rather than an Object. see below

List < String > list = new ArrayList < String > ();

list.add("hello");

String a = list.get(0);

see how the collection just returned a String, rather than an Object? the feature isn't limited to collections, you can write your own parameterized classes and interfaces. too much for me to go into here, but there are plenty of tutorials - and a whole forum here dedicated to them.

finally, I said above that you could reasonably trust the collection to hold the right types. that's because there are ways around the mechanism, largely because the extra type information doesn't exist at runtime. it's not too hard to fool the system

List < String > list = new ArrayList < String > ();

List theList = list;

theList.add(new Socket());

String a = list.get(0); //ClassCastException at runtime

get hold of a tutorial, it'll explain it much better than I just did

georgemca at 2007-7-11 23:16:20 > top of Java-index,Core,Core APIs...
# 2

List<String> list = new ArrayList<String>();

if you have a class Address with (city, state)

then

List<Address> list = new ArrayList<Address>();

list.add(new Address("Memphis", "TN");

fastmikea at 2007-7-11 23:16:20 > top of Java-index,Core,Core APIs...
# 3

generally the aspect "generics" are the very dynamic aspects availabe with the java 1.5 version. it ensures that the type safety should take place in sthe system. it means that when you are a value which is in type 'string' can only be added to that type of list. but it is only compile time checking. in runtime it is simple as the following format...

code:

List<String> lsob = new ArrayList<String>();

after compile:

List lsob=new ArrayList();

subhaja at 2007-7-11 23:16:20 > top of Java-index,Core,Core APIs...
# 4
HiI thank you all for fine replies.
myque-ans@soona at 2007-7-11 23:16:20 > top of Java-index,Core,Core APIs...
# 5
most welcome
subhaja at 2007-7-11 23:16:20 > top of Java-index,Core,Core APIs...
# 6
thanks also to myqueans@soon for give us chance to discuss
subhaja at 2007-7-11 23:16:20 > top of Java-index,Core,Core APIs...