Adding values to Arraylist
java
Solution
First simple rule: never use the `String(String)` constructor, it is absolutely useless (*).
So `arr.add("ss")` is just fine.
With `3` it's slightly different: `3` is an `int` literal, which is not an object. Only objects can be put into a `List`. So the `int` will need to be converted into an `Integer` object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as `Integer.valueOf(3)` which can (and will) avoid creating a new `Integer` instance in some cases.
So actually writing `arr.add(3)` is usually a better idea than using `arr.add(new Integer(3))`, because it can avoid creating a new `Integer` object and instead reuse and existing one.
Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.
(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)
Problem
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..