why am i getting the warning [unchecked] unchecked conversion?

2.2k views Asked by At

Can anyone please point me what I am missing over in the below statements?
Warning 1

 prog.java:16: warning: [unchecked] unchecked conversion
        adj = new LinkedList[v];
              ^
  required: LinkedList<Integer>[]
  found:    LinkedList[]

Warning 2

prog.java:18: warning: [unchecked] unchecked conversion
            adj[i] = new LinkedList();
                     ^
  required: LinkedList<Integer>
  found:    LinkedList

Warning 3

prog.java:43: warning: [unchecked] unchecked call to push(E) as a member of the raw type Stack
        stack.push(new Integer(v));
                  ^
  where E is a type-variable:
    E extends Object declared in class Stack

help me to recover this warning.Thanks in advance
PC :- keep_smiling

3

There are 3 answers

2
Akash_Triv3di On

warning 1 and 2 arises because you are not using generics properly.Cast your LinkedList to a generic type rather than raw type e.g LinkedList <Integer>.

I cant tell about the third as you should provide the code tempelate.

2
alirabiee On

Because you are using generic data-structures and your variables do not match the exact generic type where you are receiving the warnings. To be more accurate, it happens when the right-hand-side generic type is not the same or a sub-type of the left-hand-side generic type.

For example if you have:

List<String> x;

If you do something like:

x = new ArrayList();

You will get an unchecked warning, because x's generic type, i.e. String, is not the same or a super-type of the right-hand-side generic type Object which is the default for List.

1
Ramin Taghizada On

just put

@SuppressWarnings("unchecked") 

above your method;

For example:

class Graph { 
    private int V;
    private LinkedList <Integer> adj[]; 

    @SuppressWarnings("unchecked")
    Graph(int v) { 
       V = v; 
       adj = new LinkedList[v];
       for (int i=1; i<=v; i++) 
          adj[i] = new LinkedList<Integer>(); 
    } 
}

There is one problem here , when we use

adj = new LinkedList<Integer>[v]; rather than adj = new LinkedList[v]

the compiler throws error cannot use generic type, so by adding above condition @SuppressWarnings("unchecked") solves this problem.