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
OR
List
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.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.
hi
ReplyDeletenice blog,
cheers,
lolotechie.com
But this is not the real use of generics,although I accept that its helpful in scenarios, can you actually elaborate the generics usage that includes type parameters as well.
ReplyDelete--Deepak
I always wanted to learn this stuff.. lol I never knew anything about computers thank you
ReplyDeleteHm..I do not understand the java language but it is good info
ReplyDeleteVery nice and informative blog you have here. Good work! And I followed you to keep up with your post.
ReplyDeleteSee you around my friend.
Steinar Arason
www.traffic-payout.blogspot.com
"Improve Your Blog"
HI i never did understand Java but maybe its time to start as it looks as i could learn a lot right here
ReplyDeleteHi,
ReplyDeleteAutoboxing is a great feature provided by JAVA5 but using it blindly may result in very subtle problem which will take hours and hours to
debug and find. to read more see the link
What is the problem while using '==' in autoboxing world in Java 5 ?
Thanks
Javin
fantastic post man, you have indeed covered the generics with good detail with code examples. you can also include about writing type-safe classes and interfaces. by the way I have also blogged my experience as 10 points on generics in java let me know how do you find it.
ReplyDeleteNice blog
ReplyDelete