我正在阅读《使用 Java 的面向对象的数据结构》一书,我在第 2 章。我决定尝试其中的一个练习,但代码似乎对我不起作用,即使它们直接来自书中. 任何人都可以澄清这一点吗?
package chapter2;
public interface StringLogInterface
{
void insert(String element);
boolean isFull();
int size();
boolean contains(String element);
void clear();
String getName();
String toString();
}
这个项目使用了三个文件,我把剩下的两个贴在下面。
package chapter2;
public class ArrayStringLog
{
protected String name;
protected String[] log;
protected int lastIndex = -1;
public ArrayStringLog(String name, int maxSize)
{
log = new String[maxSize];
this.name = name;
}
public ArrayStringLog(String name)
{
log = new String[100];
this.name = name;
}
public void insert(String element)
{
lastIndex++;
log[lastIndex] = element;
}
public boolean isFull()
{
if (lastIndex == (log.length - 1))
return true;
else
return false;
}
public int size()
{
return (lastIndex + 1);
}
public boolean contains(String element)
{
int location = 0;
while (location <= lastIndex)
{
if (element.equalsIgnoreCase(log[location])) // if they match
return true;
else
location++;
}
return false;
}
public void clear()
{
for (int i = 0; i <= lastIndex; i++)
log[i] = null;
lastIndex = -1;
}
public String getName()
{
return name;
}
public String toString()
{
String logString = "Log: " + name + "\n\n";
for (int i = 0; i <= lastIndex; i++)
logString = logString + (i+1) + ". " + log[i] + "\n";
return logString;
}
}
最后部分:
package chapter2;
public class UseStringLog
{
public static void main(String[] args)
{
StringLogInterface sample;
sample = new ArrayStringLog("Example Use");
sample.insert("Elvis");
sample.insert("King Louis XII");
sample.insert("Captain Kirk");
System.out.println(sample);
System.out.println("The size of the log is " + sample.size());
System.out.println("Elvis is in the log: " + sample.contains("Elvis"));
System.out.println("Santa is in the log: " + sample.contains("Santa"));
}
}
最后一部分让我感到困惑。在线上,
sample = new ArrayStringLog("Example Use");
NetBeans 说“无与伦比的类型,需要:StringLogInterface,找到:ArrayStringLog。
他们都成功构建了,但是最后一个带有三个 println 语句的文件不应该打印出一些东西吗?