Simple LinkedList will not let me add .add (int);

4

I'm practicing with some tutorials and I had a problem. Can not I add a int object to the list?

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 in list.add(5); that when I execute it I throw 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!

    
asked by Popplar 14.01.2016 в 16:23
source

1 answer

7

The issue with Java is that Lists are collections; and the collections use something called type erasure, or generics . In short, you can initialize a list only with types of a class. In your case you want to add a int that is a primitive value, not an object. What you can do to add that value would be the following:

LinkedList<Object> list = new LinkedList<>();
Integer intToAdd = new Integer(5);
list.add(intToAdd);

The class Integer works like a wrapper for primitive values of type int . In that way you pass as a parameter that the list accepts values of type Object (it is the class "source", in a few words).

    
answered by 14.01.2016 / 17:11
source