【发布时间】:2018-09-02 21:52:39
【问题描述】:
概述-
这是一个概念上的疑问。
我想实现一个数据结构来跟踪注册的手机。
所以我创建了三个类-
1) 有两个变量的节点类 -
class Node{
public Object data;
public Node next;
public Node (Object datax) {
this.data = datax;
}
}
2) 手机类
class MobilePhone {
public int phoneID;
public MobilePhone(int number) {
this.phoneID= number;
}
public int number() {
return this.phoneID;
}}<br>
3) 一个 Myset 类,它使用 Node 对象实现 LinkedList。
为了简单起见,我只是在这里展示了插入方法。
// the following method inserts a MobilePhone object in front of the Myset LL
public void Insert(Object o) {
if(IsMember(o)) {
// print already a list
return;
}
Node temp = head;
head = new Node(o);
head.next = temp;
numberPhone++;
}
然后在我使用的另一个类中
MobilePhone m1MobilePhone = new MobilePhone(193);
set1Myset.Insert(m1MobilePhone);
System.out.println(set1Myset.head.data.number());
我只使用 Object 类对象定义了 Node 类和 Myset 以便概括。
但是,如果我传递 MobilePhone 类型的对象,我将无法使用 MobilePhone 类中定义的方法,因为编译器会不断显示诸如此类的错误 -
“方法 number() 未定义类型对象”。
我的问题是,如果我已经定义了我要传递的对象的数据类型,那么为什么我不能使用为该数据类型定义的方法呢?
我应该怎么做才能使用它们?
【问题讨论】:
-
你需要使用泛型。
-
您能详细说明一下吗?