当前位置: 首页 > 知识库问答 >
问题:

Java compareTo (Object obj)

景建业
2023-03-14

我已经给了一个安慰,这是它本身的最后一天。我做了大部分工作,但在最后一个问题中,我在创建 compareTo() 函数时遇到了问题。

这就是它想要我们做的;

比较到

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

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

这是我的全部文件。java文件

类文档{私有字符串文本;

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

,这是它自己的测试文件。

import java.util.Arrays;

公共类作业2扩展文档{

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

我想问的是,我无法比较电子邮件中的对象。java和文件。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();
}

}//文件

共有3个答案

冉弘化
2023-03-14

您所做的错误在错误消息中。

只能对实现Comparable的类的对象进行排序。你的班级没有。

当您对许多不同类型的类型进行排序时,您可能希望改为提供自定义比较器,或者使文档实现可比较。

丁立果
2023-03-14

它失败的确切原因是因为您尝试在未实现可比较的类上调用 Arrays.sort

实现可比允许

  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

电子邮件未实现可比较接口

使用

public class Email implements Comparable<Email> 

http://www.javapractices.com/topic/TopicAction.do?Id=10,读读这篇文章,帮你自己一个忙

另一个注意事项是你说你想比较

电子邮件.java和文件.java

您需要一个基于逻辑的自定义函数。

compareTo用于比较相同类型的两个实例。这也意味着该函数存在于Email类中

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

myEmail.compareTo(hisEmail);
阎唯
2023-03-14

您将compareTo方法放在哪里了?如果您尝试对Document的数组进行排序,您需要让Document实现可比较(或传入一个比较器):

public class Document implements Comparable<Document> {

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

public class Document implements Comparable {

然后将compareTo放入文档

 类似资料:

相关问答

相关文章

相关阅读