I am using Eclipse JUno ,I am having trouble with the .add() of the arraylist guys please help.here is my code
import java.util.ArrayList;
public class A
{
public static void main(String[] args)
{
ArrayList list=new ArrayList();
list.add(90);
list.add(9.9);
list.add("abc");
list.add(true);
System.out.println(list);
}
}
the error which is coming is :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method add(int, Object) in the type ArrayList is not applicable for the arguments (int)
The method add(Object) in the type ArrayList is not applicable for the arguments (double)
The method add(Object) in the type ArrayList is not applicable for the arguments (boolean)
at A.main(A.java:7)
but here is the weird thing ,that the line
list.add("abc");
is not causing any error.. ADD method of list take one argument which is an object type then why i am facing this problem please help guys..i had searched a lot i did not get any solution.I have to do practice on this and due to this error i cant continue my practice..
I suppose that you're using java prior version 1.5. Autoboxing was introduced in java 1.5. And your code compiles fine on java 1.5+.
Compile as source 1.4:
With 1.5 (or later):
I suggest you to update your java or box all primitives to objects manually, as @SoulDZIN suggested.
Works great with JDK 6
Printed result :[90, 9.9, abc, true].
If still you are using lesser version than jdk 6.Please specify version.
Notice that the 'add' method is failing for the data types:
int, double, and boolean.
These are all primitive data types and not 'Objects', which the method is expecting. I believe that autoboxing is not occurring here because you are using literal values, I'm not sure about this though. Nevertheless, to fix this, use the associated Object type of each primitive:
SOURCE: Experience
EDIT:
I always try to specify the type of my Collection, even if it is an Object.
However, apparently this isn't a good practice if you are running Java 1.4 or less.