Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values to Arraylist

Tags:

java

Code 1:

ArrayList arr = new ArrayList();
arr.add(3);
arr.add("ss");

Code 2:

ArrayList<Object> arr = new ArrayList<Object>();
arr.add(3);
arr.add("ss");

Code 3:

ArrayList<Object> arr = new ArrayList<Object>();
arr.add(new Integer(3));
arr.add(new String("ss"));

all the above three codes are working fine.. can some one tell me the which is prefered and why.. and why the eclipse compiler always gives warning when type of arguments are not mentioned to the Arraylist.. thanks in advance..

like image 681
Sandeep P Avatar asked May 29 '12 10:05

Sandeep P


People also ask

How do you add values to a list in Java?

There are two methods to add elements to the list. add(E e): appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created. add(int index, E element): inserts the element at the given index.

How do you add an element to an ArrayList at a specific index?

The java. util. ArrayList. add(int index, E elemen) method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).


1 Answers

There's a faster and easy way in Java 9 without involving much of code: Using Collection Factory methods:

List<String> list = List.of("first", "second", "third");
like image 200
Rahul Raj Avatar answered Sep 19 '22 22:09

Rahul Raj