Reputation: 49
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.
Here is what it does want from us ;
compareTo
public int compareTo(java.lang.Object other)
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
class Document { private String text;
/**
* 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;
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);
}
}
}
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. 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..
/**
* 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
Upvotes: 0
Views: 35103
Reputation: 14943
The exact reason it is failing is because you are trying to call Arrays.sort
on a class that does not implement comparable
Implementing Comparable allows
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
use
public class Email implements Comparable<Email>
read this to do yourself a favor http://www.javapractices.com/topic/TopicAction.do?Id=10
The other note is you said you want to compare
Email.java and File.java
You will need a custom function for that based on the logic.
compareTo is used to compare two instances of the same type. It also means that the function lives in the Email class
Email myEmail = new Email();
Email hisEmail = new Email();
myEmail.compareTo(hisEmail);
Upvotes: 1
Reputation: 6616
try this:
Here is my whole Document.java file
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
*/
....}
Upvotes: 0
Reputation: 81074
Where did you put the compareTo
method? If you're trying to sort an array of Document
s, you need to have Document implement Comparable (or pass in a Comparator):
public class Document implements Comparable<Document> {
Or, if for some bizarre reason you're not allowed to use generics:
public class Document implements Comparable {
Then put compareTo
within Document
.
Upvotes: 2
Reputation: 533492
What you are doing wrong is in the error message.
You can only sort objects for classes which implement Comparable. Your class does not.
As you are sorting a number of different types you may want to provide a custom Comparator instead, or make Document implement Comparable.
Upvotes: 0