字符串不被视为对象吗?

Jam*_*mes 2 java interface

我不明白的是,当一个String实际上是一个对象时,为什么我在编译代码时遇到错误,而编译器则另有说法.我不知道为什么我一直收到此错误消息

  symbol:   method compareTo(Object)
  location: variable least of type Object
.\DataSet.java:17: error: cannot find symbol
   else if(maximum.compareTo(x) < 0)
Run Code Online (Sandbox Code Playgroud)

这是代码.我正在尝试使用类似的类来允许两个对象使用compareTo方法.在测试器中,我只是尝试使用基本的字符串对象进行比较.

public class DataSetTester
{
public static void main(String[] args)
{
    DataSet ds = new DataSet();
    String man = "dog";
    String woman = "cat";
    ds.add(man);
    ds.add(woman);
    System.out.println("Maximum Word: " + ds.getMaximum());


 }
}
Run Code Online (Sandbox Code Playgroud)

类:

public class DataSet implements Comparable 
{
 private Object maximum;
 private Object least;
 private int count;
 private int answer;

 public void add(Object 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 int compareTo(Object anObject)
 {
     return this.compareTo(anObject);
 }

 public Object getMaximum()
 {
  return maximum;
 }

 public Object getLeast()
 {
   return least;
 }
}
Run Code Online (Sandbox Code Playgroud)

可比接口:

public interface Comparable
{
    public int compareTo(Object anObject);
}
Run Code Online (Sandbox Code Playgroud)

duf*_*ymo 7

当然String是一个Object.

可比较现在是通用的.如果它们是String类型,为什么你觉得需要创建那些引用Object?你的代码很差; 这不是Java问题.

我不明白为什么DataSet需要实现Comparable.您只需要在添加时比较传入的字符串.这样做,你会更好:

public class DataSet {
    private String maximum;
    private String least;
    private int count;
    private int answer;

    public void add(String 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 String getMaximum() { return this.maximum; }

    public String getLeast() { return this.least; }

    public int getCount() { return this.count; }
}
Run Code Online (Sandbox Code Playgroud)