Showing posts with label collection in java 5. Show all posts
Showing posts with label collection in java 5. Show all posts

Saturday, July 18, 2009

Generics in Java 5

Arrays in Java have always been type safe. For example, an array declared as type integer can only accept integers (not String, Dog, Cat). But, collections are not like that. There is no syntax for declaring type safe collections in pre java 5. To create an ArrayList of integers, you would say:

ArrayList lst = new ArrayList();

Similarly, for creating ArrayList of String, you would say:

ArrayList lst = new ArrayList();

There is no difference between the above two declarations. They are declared of type integer and String respectively, but you can put anything into it. Like, Dog object, Cat Object as so on.

As of java 5, you can use type safe collections. If you want to create an ArrayList of type String, you would say,


ArrayList lst = new ArrayList();
OR
List lst = new ArrayList();



How you add elements to collection in pre java 5?

List lst = new ArrayList ();
lst.add (“Danny”);
lst.add (new Cat ());
lst.add (new Double ());

As you can see, a non- generic collection can hold any kind of Object.


How you add elements to collection in java 5?

List lst = new ArrayList ();
lst.add (“Danny”);
lst.add (“Katty”);
lst.add (new Cat ()); // Compilation Error


You can’t add Cat object in lst ArrayList – You can add only and only Strings.


How to get objects from collection in Pre java 5?

In pre-java 5, the method that get objects out from collection could have only one kind of return type – java.lang.Object. If you want to get element from String list, you require a cast to do so.

String element = (String) lst.get (0);

and since, you can’t guarantee that what is coming out really is a String, the cast could fail at run time.

How to get objects from collection in java 5?

By using generic syntax, you can ensure that what is coming out is what you have added. So, no cast is required here.

String element = lst.get (0);

You are sure that lst List holds only Strings, so no cast is required here.