0

我给了一个任务,它本身的最后一天。我做了大部分,但在最后一个问题上,我在创建 compareTo() 函数时遇到了问题。

这就是它对我们的要求;

相比于

public int compareTo(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 文件

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

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

公共类 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);
    }
}
}

我想问的是,我无法比较我的 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();
}

} // 文件

4

4 回答 4

2

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

public class Document implements Comparable<Document> {

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

public class Document implements Comparable {

然后compareTo放入Document.

于 2012-04-10T16:29:09.547 回答
1

它失败的确切原因是因为您试图调用Arrays.sort一个没有实现可比较的类

实施 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

电子邮件没有实现 Comparable 接口

利用

public class Email implements Comparable<Email> 

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

另一个说明是你说你想比较

Email.java 和 File.java

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

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

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

myEmail.compareTo(hisEmail);
于 2012-04-10T16:29:53.290 回答
0

您做错了什么在错误消息中。

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

当您对许多不同的类型进行排序时,您可能希望提供自定义 Comparator,或者使 Document 实现 Comparable。

于 2012-04-10T16:28:44.273 回答
0

尝试这个:

这是我的整个 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
*/
....}
于 2012-04-10T16:31:24.833 回答