Solved

Arraylist declaration

Posted on 2013-11-25
2
322 Views
Last Modified: 2013-11-26
Hi,

What are the advantages of declaring ArrayList as below as of J2SE5.0

ArrayList<Student> students = new ArrayList<Student>();
vs as below as J2SE 1.4
ArrayList students = new ArrayList();

please advise
Any links resources ideas highly appreciated. Thanks in advance
0
Comment
Question by:gudii9
2 Comments
 
LVL 27

Accepted Solution

by:
dpearson earned 300 total points
ID: 39676157
The first form makes it clear that the Objects in the list are Students.

The second form - you just have a list of Objects - anything could be in there (Students, Integers, etc.).

List<Student> newStudents = new ArrayList<Student>() ;
List oldStudents = new ArrayList() ;

Student student1 = newStudents.get(0) ; // Note: no cast in Java 5
Student student2 = (Student)oldStudents.get(0) ; // Have to cast to get the value
Integer student3 = (Integer)oldStudets.get(0) ; // Whoops - cast to wrong type - won't get an error until I run this code

Doug
0
 
LVL 12

Assisted Solution

by:Sharon Seth
Sharon Seth earned 200 total points
ID: 39676788
Some more points on this:

This feature is called Generics . It is for compile time type checking  , which would otherwise give you a nasty class cast exception during run time . As Doug put in his student sample , with generics , the compiler always makes sure that you only use that list for students .

Note that this has been implemented only in the compiler and not in the JVM . JVM does not know/recognise generics .
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question