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 をインポートします。

public class Homework2 extends 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 のオブジェクトを比較できないことです。ドキュメント [] 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

もう1つのメモは、比較したいと言ったことです

Email.java と File.java

ロジックに基づいて、そのためのカスタム関数が必要になります。

compareTo は、同じ型の 2 つのインスタンスを比較するために使用されます。また、関数が 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 に答える