【发布时间】:2016-04-12 01:55:34
【问题描述】:
这是我的课:
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node (){}
public Node (int x)
{
data = x;
}
public int data()
{
return data;
}
public Node next()
{
return next;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
这是我的界面:
public interface Set {
public boolean isEmpty();
public void makeEmpty();
public boolean isMember(int x);
public void add(int x);
public void remove(int y);
public void union(Set other, Set result);
public void intersection (Set other, Set result);
public void difference (Set other, Set result);
@Override
public String toString();
@Override
public boolean equals(Object other);
public void setList(int i); //i added this to use it as an identifier for each
//list element in the set array
public String getListId(); //these two extra methods make life easier
}
我有一个这样的方法(在LinkedListSet 类中):
public void difference (Set other, Set result)
{
if (other.isEmpty())
{
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty())
{
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
differenceHelper(this.first, othr.first, res);
result = res;
}// the print statements were added for debugging
问题是,在上述方法中,我无法将Set Other 转换为其链表实现。当我在主程序中调用这个方法时,参数实际上是链表类型(所以我显然没有得到任何错误)。
但是,所有实例变量都是null。该列表在我投射它之前和之后都是空的(当它实际上不为空时)。我知道这是因为界面不包含任何有关Nodes 的信息,但是除了编辑界面以合并Node 之外,我还能做些什么吗?
我希望我已经说得够清楚了。任何帮助将不胜感激。
编辑: 在主程序中,我创建了一个 Set 数组。
Set[] sets = new Set[7];
for (int i = 0; i< sets.length; i++) //initialize each element
{
sets[i] = new LinkedListSet();
}
每个列表都有带有数据值的节点,这些数据值稍后会添加到代码中...
然后我调用差异方法。
sets[0].difference(sets[1], sets[4])
sets[1].isEmpty 出于某种原因返回 true(即使它不是)。
如果我要这样做: System.out.println(sets[1].first.data()) 我不会有任何问题。 由于某种原因,当参数传递给差异方法时,所有值都变为空。
public boolean isEmpty()
{
return first == null;
}
【问题讨论】:
-
请添加
LinkListSet差异方法实现代码。还有您实例化和使用这些类的代码。也许你在那里做错了什么。 -
不是实现代码错了。
-
问题出在方法上。我查过了。
-
抱歉,我刚刚注意到您的
difference方法实现。 -
当您在主代码中的另一个集合上调用 isEmpty 时,它是否返回 false?