1

我需要修改 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 不能应用于给定类型。

4

1 回答 1

2

您的代码包括:

 public class String implements Comparable {
      ...
 }

您是否意识到有一个标准的 Java 库类String被默认导入到每个类中?如果实现你自己的类调用String你会得到一些非常混乱的编译错误消息。

我强烈建议您将班级名称更改为其他名称;例如StringHolder


请注意,从技术上讲,您可以定义一个名为String. 然而,Java 用来消除类名称歧义的规则并不是为这个用例设计的……而且无论你在哪里使用它,你最终都必须java.lang.String通过它的完全限定名称来引用它。其他阅读/修改您的代码的人会发现这真的很尴尬/烦人。

最好将java.lang包中类的名称视为“保留”,并且不要定义具有相同(非限定)名称的类。

于 2013-02-18T00:50:51.570 回答