javalistlinked-listwarnings

Warnings when compiling a Linked List code in java


I am trying to write a simple code to implement Linked List in Java using java.util.LinkedList library. I have tried my best to keep it error-free.

It does compile (and execute) using -Xlint:unchecked. But it generates a LOT of warnings of the type - LL.java:25: warning: [unchecked] unchecked call to add(E) as a member of the raw type LinkedList

Can someone help me 1. Comprehend why is it happening? 2. Remove the warnings!

Any help will be appreciated...

import java.util.LinkedList;

class LL{
public static void main(String[] args){

    //creating a new linked list object
    LinkedList LLobj = new LinkedList();

    //adding data to linked list
    LLobj.add("T");
    LLobj.add("H");
    LLobj.add("I");
    LLobj.add("S");
    LLobj.add(" ");
    LLobj.add("I");
    LLobj.add("S");
    LLobj.add(" ");
    LLobj.add("A");
    LLobj.add(" ");
    LLobj.add("L");
    LLobj.add("I");
    LLobj.add("N");
    LLobj.add("K");
    LLobj.add("E");
    LLobj.add("D");
    LLobj.add("-");
    LLobj.add("L");
    LLobj.add("I");
    LLobj.add("S");
    LLobj.add("T");

    //printing the linked list
    System.out.println(LLobj);

    //Implementing more functions to add data
    LLobj.addFirst("#");
    LLobj.addLast("#");
    LLobj.add(5,"$");

    //printing the linked list
    System.out.println(LLobj);

    //removing data
    LLobj.remove("$");
    LLobj.remove("#");
    LLobj.remove("#");

    //printing the linked list
    System.out.println(LLobj);
    }
}

Solution

  • Well, you're using a generic type (LinkedList<E>) but you're using it as the raw type, as if you didn't know about generics. You want something like this:

    LinkedList<String> list = new LinkedList<String>();
    
    list.add("T");
    list.add("H");
    

    That way you're safe in terms of the types involved, and you know that everything in the list is a string.

    In Java 7 you can use "diamond syntax" to infer the type on the right hand side from the left:

    LinkedList<String> list = new LinkedList<>();
    

    For much more about generics (including raw types), see the Java generics FAQ. Also note how in my example I renamed your LLobj variable name (which doesn't follow Java naming conventions) to just list. It's a good idea to follow the naming conventions at all times, especially when sharing code with others.