[英]Having a hard time with generic classes and generic methods in java
New to java, I did search for examples, but I'm having a really hard time. java的新手,我确实搜索了一些例子,但我真的很难过。
I have a node class that uses generics: 我有一个使用泛型的节点类:
public class Node<T> {
private int key;
private T data;
private Node<T> nextNode;
}
The node is Okay. 节点是好的。
public class GenericDictionary implements GenericDictionary_interface {
private int capacity;
private Node<T> [] slots;
public void add (Node<T> newNode) {
}
}
This is how I would write it, I think. 我想这就是我写它的方式。 I want the GenericDictionary to work with node objects.
我希望GenericDictionary与节点对象一起使用。
I get an error: "T cannot be resolved as a Type". 我收到一个错误:“T无法解析为类型”。
Thing is I don't know how it should look like. 事情是我不知道它应该是什么样子。
Your GenericDictionary
class would need to be generic as well: 您的
GenericDictionary
类也需要是通用的:
public class GenericDictionary<T> ...
{
}
At that point, it'll be fine to use Node<T>
within the class. 那时,在类中使用
Node<T>
会很好。
If the interface contains the add
method, the interface should probably be generic too: 如果接口包含
add
方法,那么接口应该也是通用的:
public class GenericDictionary<T> implements Dictionary<T>
{
}
I'd advise against an interface called GenericDictionary_interface
, by the way... if there's only ever going to be one implementation, you could call the interface GenericDictionary
and the implementation GenericDictionaryImpl
- somewhat horrible, but reasonably common. 顺便说一句,我建议不要使用名为
GenericDictionary_interface
的接口......如果只有一个实现,你可以调用接口GenericDictionary
和实现GenericDictionaryImpl
- 有点可怕,但相当普遍。 If there are multiple implementations, name the implementation by some differentiating aspect. 如果有多个实现,请通过某些区分方面命名实现。
In your second one it doesn't have any idea what type T is so you need to add it to the declaration 在你的第二个中,它不知道T是什么类型,所以你需要将它添加到声明中
public class GenericDictionary<T> implements GenericDictionary_interface {
private int capacity;
private Node<T> [] slot;
public void add (Node newNode) {
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.