Java 比较(对象 obj)

标签 java compareto

我已经完成了一项任务,这也是最后一天了。我做了大部分工作,但在最后一个问题上,我在创建compareTo()函数时遇到了问题。

这就是它想要从我们这里得到的;

比较

public intcompareTo(java.lang.Object other)

Specified by:
    compareTo in interface java.lang.Comparable

这就是我所做的

public int compareTo(Object obj)
{
Document tmp = (Document)obj;
if(this.text < tmp.text)
{
/* instance lt received */
return -1;
}
else if(this.text > tmp.text)
{
/* instance gt received */
return 1;
}
/* instance == received */
return 0;
}

这是我的整个 Document.java 文件

类文档 { 私有(private)字符串文本;

/**
* Default constructor;  Initialize amount to zero.
*/
public Document()
{
    text = "";
}

/**
* Default constructor;  Initialize text to input value
* @param text New text value
*/
public Document(String text)
{
    this.text = text;
}

/**
* Returns as a string the contents of the Document.
*/
public String toString()
{
    return text;
}

这是它本身的测试文件。

导入java.util.Arrays;

公共(public)类 Homework2 扩展了 Document {

/** ======================
* ContainsKeyword
* Returns true if the Document
* object passed in contains keyword as a substring
* of its text property.
* ======================
*/
public static boolean ContainsKeyword(Document docObject, String keyword)
{
    if (docObject.toString().indexOf(keyword,0) >= 0)
        return true;
    return false;
}


public static void main(String[] args){

    Email email1= new Email("Programming in Java",
            "Larry", "Curly", "Programming");
    Email email2 = new Email("Running marathons",
            "Speedy", "Gonzales", "races");

    System.out.println(email1);

    File file1 = new File("Some Java file", "file.txt");
    File file2 = new File(
            "Boluspor wins against Besiktas. Muahahahaha", 
    "bolutas.txt");

    Document doc = new Document (
    "ok?,ok?,ok?,ok?,ok?,ok?,ok?,ok?,ok?,ok?,ok?,ok?");

    System.out.println("\n"+file1);

    System.out.println("\nWhich contains Java?");
    if (ContainsKeyword(email1,"Java")) System.out.println(" Email1");
    if (ContainsKeyword(email2,"Java")) System.out.println(" Email2");
    if (ContainsKeyword(file1,"Java")) System.out.println(" File1");
    if (ContainsKeyword(file2,"Java")) System.out.println(" File2");

    Document [] da = new Document [5];
    da[0] = email1;
    da[1] = email2;
    da[2] = file1;
    da[3] = file2;
    da[4] = doc;
    Arrays.sort(da);
    System.out.println("\nAfter sort:");
    for(Document d : da){
        System.out.println(d);
    }
}
}

我想问的是,我无法比较 Email.java 和 File.java 中的对象,我可以做任何其他事情,但最后一部分以 Document [] da... 开头,该部分给出了错误。我在这里做错了什么?

错误是;

Exception in thread "main" java.lang.ClassCastException: Email cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at Homework2.main(Homework2.java:53)

上传**这是我的电子邮件和文件类..

/**
* First define class for Email, derive from Document
*/
class Email extends Document
{
    private String sender;
    private String recipient;
    private String title;
    private String body;

    /**
    * Constructors
    */
    public Email()
    {
        super();
        sender = "";
        recipient = "";
        title = "";
        body = "";
    }

    public Email(String body, String sender, String recipient, String title)
    {

        this.sender = sender;
        this.recipient = recipient;
        this.title = title;
        this.body = body;
    }

   // ======================
   // Various accessor and mutator methods
   // ======================
    public String getSender()
    {
        return sender;
    }

    public void setSender(String sender)
    {
        this.sender = sender;
    }

    public String getRecipient()
    {
        return recipient;
    }

    public void setRecipient(String recipient)
    {
        this.recipient = recipient;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }
    public String getBody(){
        return body;
    }  
    public void getBody(String body){
        this.body = body;
    }

   /**
  * Returns as a string the contents of the text fields concatenated
  * together.  Uses super.toString to get the parent's text.
  */
   public String toString()
  { 
return "Sender:" + sender + ",Recipient:" + recipient + ",Title:" + title + ",Body:" + body + " " +
 super.toString();
  }
} // Email

和文件;

/**
* Next define class for File, derive from Document
* For brevity, short one-line methods are defined here in the
* header.
*/
class File extends Document
{
private String pathname;

/**
* Constructors.
*/
public File()
{
    super();
    pathname = "";
}

public File(String body, String pathname)
{
    super(body);
    this.pathname = pathname;
}

// ======================
// Various accessor and mutator methods
// ======================
public void setPathname(String s)
{
    pathname = s;
}

public String getPathname()
{
    return pathname;
}

/**
* Returns as a string the contents of the text fields concatenated
* together.  Uses super.toString to get the parent's text.
*/
public String toString()
{
    return "Pathname " + pathname + " Body " + super.toString();
}

}//文件

最佳答案

你把compareTo方法放在哪里了?如果您尝试对 Document 数组进行排序,则需要让 Document 实现 Comparable(或传入 Comparator):

public class Document implements Comparable<Document> {

或者,如果由于某种奇怪的原因不允许您使用泛型:

public class Document implements Comparable {

然后将compareTo放入Document中。

关于Java 比较(对象 obj),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10092602/

相关文章:

Java:没有编译错误,但我的输出是错误的

java - 在 Java 中对插入数组的字符串进行排序

java - 重写整个 String 类方法

java - 使用 Comparable 接口(interface)时,compareTo() 方法未覆盖默认方法

java - 如何使用 android studio 以编程方式记录 Android 设备的所有入站和出站连接

java - 无法为安卓游戏绘制正方形网格

java kafka 通过唯一键获取分区中的消息偏移量

java - 无法同时运行两个着色器程序,但是每个单独使用时都可以正常工作

java - 原始类型双重错误

java - 使用 compareTo 实现 equals 方法