Reputation: 11
In Line 11 there is an error .
operator < cannot be applied to java.lang.Object,java.lang.Object
I don't quite understand this but then again I'm new to generics in Java . bear with me please.
public void sortbykey()
{
LinkedList temp = new LinkedList();
LinkedList third = new LinkedList();
temp=head;
if(temp!=null)
{
while(temp.next!=null)
{
if (temp.key < temp.next.key)
{
third.item = temp.key;
temp.key = temp.next.key;
temp.next.key = third.item;
}
else
temp = temp.next;
}
}
}
Upvotes: 1
Views: 7583
Reputation: 649
To compare non-numeric types, you would need to implement Comparable
on that type and use temp.key.compareTo(temp.next.key) < 0
instead.
If you were using a LinkedList<? extends Number>
, it would not be applicable due to type erasure. However, if you specify a concrete implementation that wraps a primitive to which the <
operator is applicable (see autoboxing) such as LinkedList<Integer>
, then it would be possible since Integer
is specified as the bound, Integer
wraps int
, and the <
operator is applicable to int
.
In your case, since you are using a raw type, the bound is java.lang.Object
, to which the <
operator is not applicable. Just like those of us reading your question, we can't tell if the LinkedList
is of a type to which the <
can be applied.
Raw types should be generally avoided anyway as they effectively strip generics of their value.
Upvotes: 5
Reputation: 134
I can't tell for sure because you haven't posted the data structure of your Node and LinkedList, but it looks like whatever you're storing in 'key' is not a java primitive so you can't use the '<' operator. make sure key is something like an int or float to use <. Otherwise you will need to use a class method on the type of 'key'. For example if 'key' is a String, you could use ("apple").compareTo("banana");
Upvotes: 0
Reputation: 62864
Simply, this operator can be applied on numeric types, such as int
, byte
, double
, float
, etc and their boxing classes (such as Integer
, Byte
, etc.).
It doesn't work combined with Generics, because the compiler doesn't know the exact types of the operands. When working with Generics, these types are set at Runtime, after the type erasure has occurred.
A possible solution for you is to make the class of the key
property implement the Comparable<T>
interface and then you will be able to compare it with:
temp.key.compareTo(temp.next.key) > 0
Upvotes: 2