简体   繁体   English

Java compareTo(对象对象)

[英]Java compareTo (Object obj)

I've given an assigment and its the last day of itself.我已经给出了一个分配,它本身就是最后一天。 I did most of it but on the last question I have a problem with creating a compareTo() function.我做了大部分,但在最后一个问题上,我在创建 compareTo() function 时遇到了问题。

Here is what it does want from us;这就是它对我们的要求;

compareTo相比于

public int compareTo(java.lang.Object other) public int compareTo(java.lang.Object 其他)

Specified by:
    compareTo in interface java.lang.Comparable

Here is what I did这是我所做的

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;
}

Here is my whole Document.java file这是我的整个 Document.java 文件

class Document { private String text; class 文档 { 私有字符串文本;

/**
* 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;
}

and Here is the test file of itself.这是它自己的测试文件。

import java.util.Arrays;导入 java.util.Arrays;

public class Homework2 extends Document {公共 class Homework2 扩展文档 {

/** ======================
* 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);
    }
}
}

What I wanted to ask is, I cannot compare the objects from my Email.java and File.java, I can do anything else but the last part which starts with Document [] da... That part gives an error.我想问的是,我无法比较我的 Email.java 和 File.java 中的对象,除了以 Document [] da 开头的最后一部分之外,我可以做任何其他事情......那部分给出了错误。 What am I doing wrong here?我在这里做错了什么?

The error is;错误是;

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)

UPLOAD ** Here is my Email and File Class..上传 **这是我的 Email 和文件 Class..

/**
* 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

and File;和文件;

/**
* 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();
}

} // File } // 文件

Where did you put the compareTo method?你把compareTo方法放在哪里了? If you're trying to sort an array of Document s, you need to have Document implement Comparable (or pass in a Comparator):如果您尝试对Document的数组进行排序,则需要让 Document 实现 Comparable(或传入 Comparator):

public class Document implements Comparable<Document> {

Or, if for some bizarre reason you're not allowed to use generics:或者,如果出于某些奇怪的原因不允许您使用 generics:

public class Document implements Comparable {

Then put compareTo within Document .然后将compareTo放在Document中。

The exact reason it is failing is because you are trying to call Arrays.sort on a class that does not implement comparable它失败的确切原因是因为您试图在未实现可比较的 class 上调用Arrays.sort

Implementing Comparable allows实施 Comparable 允许

 calling Collections.sort and Collections.binarySearch calling Arrays.sort and Arrays.binarySearch using objects as keys in a TreeMap using objects as elements in a TreeSet

Email did not implement the Comparable interface Email 没有实现Comparable接口

use采用

public class Email implements Comparable<Email> 

read this to do yourself a favor http://www.javapractices.com/topic/TopicAction.do?Id=10阅读本文以帮自己一个忙http://www.javapractices.com/topic/TopicAction.do?Id=10

The other note is you said you want to compare另一个注意是你说你想比较

Email.java and File.java Email.java 和 File.java

You will need a custom function for that based on the logic.您将需要一个基于逻辑的自定义 function。

compareTo is used to compare two instances of the same type. compareTo 用于比较同一类型的两个实例。 It also means that the function lives in the Email class这也意味着 function 住在 Email class

Email myEmail = new Email();
Email hisEmail = new Email();

myEmail.compareTo(hisEmail);

What you are doing wrong is in the error message.你做错了什么在错误信息中。

You can only sort objects for classes which implement Comparable.您只能对实现 Comparable 的类的对象进行排序。 Your class does not.你的 class 没有。

As you are sorting a number of different types you may want to provide a custom Comparator instead, or make Document implement Comparable.当您对许多不同类型进行排序时,您可能希望提供自定义比较器,或者使文档实现可比较。

try this:试试这个:

Here is my whole Document.java file这是我的整个 Document.java 文件

class Document implements Comparable { //this line is your solution.
 private String text;

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

/**
* Default constructor;  Initialize text to input value
* @param text New text value
*/
....}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM