我需要修改DataSet以接受Comparable Objects。测试人员不会编译,我不知道如何打印compareTo方法。我应该为测试人员使用ArrayList吗?提前谢谢!
public interface Comparable
{
/**
Compares this object with another.
@param other the object to be compared
@return a negative integer, zero, or a positive integer if this object
is less than, equal to, or greater than, other
*/
int compareTo(Object other);
}
public class DataSetComparable
{
private double sum;
private Object maximum;
private Object minimum;
private int count;
private Comparable comparer;
/**
Constructs an empty data set with a given measurer.
@param aMeasurer the measurer that is used to measure data values
*/
public DataSetComparable(Comparable acomparer)
{
sum = 0;
count = 0;
maximum = null;
minimum = null;
comparer= acomparer;
}
/**
Adds a data value to the data set.
@param x a data value
*/
public void add(Object x)
{
sum = sum + comparer.compareTo(x);
if (count == 0 || comparer.compareTo(maximum) < comparer.compareTo(x))
maximum = x;
if (count == 0 || comparer.compareTo(minimum) > comparer.compareTo(x))
minimum=x;
count++;
}
/**
Gets the largest of the added data.
@return the maximum or 0 if no data has been added
*/
public Object getMaximum()
{
return maximum;
}
/**Gets the smallest of the added data.
*@return the minimum or 0 if no data has been added
**/
public Object getMinimum()
{
return minimum;
}
}
public class String implements Comparable {
private String input;
private int holder;
public String(String aninput){
input= aninput;
holder=0;
}
public String getComparer(){
return input;
}
public String getString(){
return input;
}
public int compareTo(Object other){
String temp= (String) other;
if(input.compareTo(temp)<0){
holder=-1;
}
else if (input.compareTo(temp)== 0) {
holder= 0;
}
else{
holder= 1;
}
return holder;
}
}
public class StringTester{
public static void main (String [] args){
Comparable c = new String();
DataSetComparable data = new DataSetComparable(c);
data.add(new String("Jimmy"));
data.add(new String("Amy"));
data.add(new String("Melissa"));
data.add(new String("Melissa"));
String max = (String) data.getMaximum();
String min = (String) data.getMinimum();
System.out.println("Maximum String = " + max);
System.out.println("Minimum String = " + min);
}
}
更具体地说,错误说:
构造函数类String中的String不能应用于给定的类型。
答案 0 :(得分:2)
您的代码包含以下内容:
public class String implements Comparable {
...
}
您是否意识到有一个名为String
的标准Java库类默认导入到每个类中?如果实现了你自己的一个名为String
的类,你将会得到一些非常混乱的编译错误消息。
我强烈建议您将班级名称更改为其他名称;例如StringHolder
。
注意,从技术上讲,可以定义一个名为String
的类。但是,Java用于消除类名称歧义的规则并不是针对此用例设计的......您最终必须使用完全限定名称来引用java.lang.String
,无论您在何处使用它。阅读/修改代码的其他人会觉得非常尴尬/讨厌。
最好将java.lang
包中的类名称视为“保留”,并且不要定义具有相同(非限定)名称的类。