Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unchecked Cast warning in Java?

Tags:

java

In this code I am making an implementation of a generic linkedlist in java.

public class LL<Item extends Comparable<Item>> {

My Node class is defined like

private class Node{
private Item data;
private Node next;
public Node(Item data){
    this.data = data;
    next = null;
}
}

Now my doubt is, I keep getting warnings when coding

 Node x = head, y = (Node) b.head;
Type safety: Unchecked cast from LL.Node to LL<Item>.Node

Should I ignore this, why does the compiler generate that. And is there a workaround it ?

EDIT :

b is of type LL, the function signature looks like

public void mergeAlternate(LL b){

And head is a private instance variable of LL class

private Node head;
like image 453
hershey92 Avatar asked Oct 21 '22 07:10

hershey92


1 Answers

If you are creating a generic implementation then it should be generic internally as well.

You are missing the type parameter for your Node class. It should be generic like this:

private class Node<T extends Comparable<T>> {
    private T data;
    private Node<T> next;
    public Node(T data){
        this.data = data;
        next = null;
    }

}

And where you are using that class you can do something like this:

new Node<Item> // ...

And your code will look like this:

Node<Item> x = head, y = b.head;

and you won't get warnings that way.

My spider sense however tells me that there is some architectural problem there. Since you did not show us all your code we can't help you any further.

like image 143
Adam Arold Avatar answered Nov 04 '22 21:11

Adam Arold