I tried to create a LinkedList class. But I had 2 problem:
1)The Node last=null
declaration is giving me a raw-type error but in above of that declaration there is no error like it. 4 same declarations but only the last one gives an error.
2) In the get()
method I want to return V type and as you can see the value variable is already in V type. But it gives me "cannot convert Object to V" error. But temp.value is already V.
public class Linkedlist<V> {
public class Node <V> {
private Node next=null;
private String key;
private int size;
private V value=null;
public Node(V value, String key){
this.key=key;
this.value=value;
}
}
Node root=null;
Node temp=null;
Node temp1=null;
Node last=null;
last=root;
public void add(V value, String key){
last.next = new Node(value,key);
last=last.next;
}
public void remove(String key){
temp=root;
if(isEmpty())
System.out.println("list is empty!");
else{
if(temp.next!=null){
if(!temp.next.key.equals(key)){
remove(temp.next.key);
}
else if(temp.next.key.equals(key)){
if(temp.next==last)
last=temp;
temp.next=temp.next.next;
}
}
else
System.out.println("there is no such element");
}
}
public V get(String key){
temp=root;
if(temp.key.equals(key)){
if(temp.next!=null)
get(temp.next.key);
else
return null;
}
else if(temp.key.equals(key))
return temp.value;
}
The two problems you cite are really one and the same. Given a parameterized class Node<V>
such as you declared, these ...
Node root=null;
Node temp=null;
Node temp1=null;
Node last=null;
... all declare objects of the raw type Node
. Other code will interpret treat them as if their type parameters had been specified as Object
. You should instead declare them like so:
Node<V> root=null;
Node<V> temp=null;
Node<V> temp1=null;
Node<V> last=null;
where the <V>
is literal -- a reference to the class's type parameter, not any concrete type. If you do that then both your errors will go away.
Your inner class Node
is generic, but you're using the raw form of the class. That means that a method that returns V
gets type-erased, and it is now returning Object
. But the Node
class doesn't need to be generic. A non- static
nested class (ie a nested class) can use its enclosing class's generic type parameter. So, remove the <V>
on the Node
class definition.
public class Node {
Other problems I see:
last=root;
appears to be outside any constructor, method, or initialization block. isEmpty()
method, but you may have not posted it for brevity. get()
method needs a return
statement in the case that neither the if
nor the else
conditions are met.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.