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..
First simple rule: never use the
String(String)constructor, it is absolutely useless (*).So
arr.add("ss")is just fine.With
3it’s slightly different:3is anintliteral, which is not an object. Only objects can be put into aList. So theintwill need to be converted into anIntegerobject. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing asInteger.valueOf(3)which can (and will) avoid creating a newIntegerinstance in some cases.So actually writing
arr.add(3)is usually a better idea than usingarr.add(new Integer(3)), because it can avoid creating a newIntegerobject 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 😉