我尝试查找教程和视频,并了解实现的内容,尽管我对如何从Java库实现类感到困惑。在我的作业中,我想要利用类DataSet并使其接受Comparable对象。该程序假设根据对象记录最小值和最大值,在这种情况下,我想使用字符串。我不确定我是否需要任何类来实现Comparable接口,所以我做了两个类以防万一我想这样做。我真正的问题是如何在测试器类中实际包含一个String变量来实际读取并将对象与另一个对象进行比较?提前谢谢。
public class Word implements Comparable
{
private String str;
public Word()
{
str = null;
}
public Word(String s)
{
str = s;
}
public int compareTo(Object other)
{
String n = (String) other;
return str.compareTo(n);
}
}
我不确定这两个类中哪一个适合实现虽然我认为下面的String类根本不起作用b / c它已经是标准类所以我不太确定使用它
public class String implements Comparable
{
public String s;
public String()
{
s = null;
}
public String(String str)
{
s = str;
}
public int compareTo(Object other)
{
String n = (String) other;
return s.compareTo(n);
}
}
public interface Comparable
{
public int compareTo(Object other);
}
public class DataSet
{
private Object maximum;
private Object least;
private Comparable compare;
private int count;
public DataSet(Comparable s)
{
compare = s;
}
public void add(Object x)
{
if(count == 0)
least = x;
if(count == 0 || compare.compareTo(x) >=0)
maximum = x;
else if(compare.compareTo(x) <0)
least = x;
count++;
}
public Object getMaximum()
{
return maximum;
}
public Object getLeast()
{
return least;
}
}
public class DataSetTester
{
public static void main(String[] args)
{
Comparable n = new Word("sand");
DataSet data = new DataSet(n);
data.add(new Word(man));
System.out.println("Maximum Word: " + data.getMaximum());
System.out.println("Least Word: " + data.getLeast());
}
}
答案 0 :(得分:0)
接口是一个合同,表明您的类包含接口中实现的所有方法。在这种情况下CompareTo(object other)
。 String类已经实现了类似的接口,因此您不需要自己的类。我认为你的数据集类应该是这样的:
public class DataSet<T implements Comparable>
{
private T maximum;
private T least;
private T count;
public void add(T x)
{
if(count == 0){
least = x;
maximum = x;
}
else if(least.compareTo(x) > 0)
least = x;
else if(maximum.compareTo(x) < 0)
maximum = x;
count++;
}
public T getMaximum()
{
return maximum;
}
public T getLeast()
{
return least;
}
}
T是泛型类型,在您的情况下它应该是String,以下是创建新数据集的方法:
DataSet<String> ds = new DataSet<String>;