I'm practicing with some tutorials and I had a problem. I can't add an object to the list int
?
package paquete;
import java.util.*;
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList list = new LinkedList();
list.add("Perro");
list.add(0, "Gato");
list.add(5);
The problem is list.add(5);
that when I run it I get this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method add(int, Object) in the type LinkedList is not applicable for the arguments (int)
at package.Main.main(Main.java:14)
I hope you can help me!
The thing with Java is that Lists are collections; and collections use something called type erasure, or generics . In a nutshell, you can initialize a list with only types of a class. In your case you want to add a
int
which is a primitive value, not an object. What you can do to add that value would be the following:The Integer class works as a wrapper for primitive values of type
int
. That way you pass as a parameter that the list accepts values of type Object (it's the "source" class, in a nutshell).