Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an ArrayList in Java? [duplicate]

Possible Duplicate:
List versus ArrayList as reference type?

Whats the difference in creating an arraylist in the following ways?

List listA = new ArrayList(); and ArrayList alist = new ArrayList();
like image 911
user1723254 Avatar asked Jul 16 '26 01:07

user1723254


1 Answers

The first assigns a list to a variable defined by its interface, the second defines the variable by class.

The first declaration will let you change the implementation later:

List listA = new LinkedList();

is valid, while the second would not let you change the implementation:

ArrayList listA = new LinkedList(); // <<<=== INVALID

It is worth noting that starting with Java 5 List is a generic type, so you should specify the type parameter to improve type safety:

List<ClassA> listA = new ArrayList<ClassA>();
like image 100
Sergey Kalinichenko Avatar answered Jul 17 '26 14:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!