Reputation: 8985
I have this linked list class implementation LinkedList
which contains a method getMode
public class LinkedList<AnyType extends Comparable<? super AnyType>>
{
//Some code...
public AnyType mode(){
//Some code...
ListNode node;
AnyType mode;
mode = node.element;
return mode;
}
}
The generic variable AnyType is type bound in this linked list class. The same variable is bound in another class ListNode
. ListNode is not declared in LinkedList. It is an independent class.
class ListNode<AnyType extends Comparable<? super AnyType>>
{
//Some code...
public AnyType element;
}
I'm wondering why the line in the linked list class
mode = node.element;
Is giving me a type incompatability error
>Required AnyType
Found java.lang.Comparable < >
The type bounds for the generic AnyType
variable is the same in both the node class and the linked list class, so I dont' see why there should be type incompatability here.
The type bound is always
<AnyType extends Comparable<? super AnyType>>
edit
Someone has mentioned a solution which appears to work. I had to specify AnyType
as a bound for the node node variable in the getMode
method, otherwise the raw type was used or something like that
public class LinkedList<AnyType extends Comparable<? super AnyType>>
{
//Some code...
public AnyType mode(){
//Some code...
ListNode<AnyType> node; // <--- here
AnyType mode;
mode = node.element;
return mode;
}
}
Upvotes: 0
Views: 60
Reputation: 3502
Because the compiler doesn't know that AnyType
from your LinkedList
is the same as the AnyType
in your ListNode
For example, LinkedList<String>
and ListNode<Integer>
are both valid (satisfy the bounds upon AnyType
), but you would probably run into a bunch of issues if a LinkedList<String>
was handling ListNode<Integer>
s.
You need to make sure that any ListNode
s inside of your LinkedList
class are all declared as ListNode<AnyType>
.
Side note, the common Java convention would be to use E
instead of AnyType
as the name of the generic element type in a collection.
Upvotes: 2