How to enforce developers to override toString() method

Hi,
Right now we are in design stage of our application. I want that all our BO classes should override toString(), equals() and hashCode() methods.
We expect that our application would be running for next 5 to 10 years, and so looking for ways to enforce these rules to developers.
One way to do is let ant script handle such validations. Another way could be using PMD to enforce rules.
These could be good ways of doing this, but my manager doesnot quite like to depend on external tools like these ... as 5 years down the line you donot know state of these tools.
Can someone suggest if java provides any such provision ...
If someone has some smart solution do let me know ... your help is much appreciated ... and thanks in advance.
Regards,
Rana Biswas

This is interesting.
toString() method is already implemented in class Object, which is inherited by all other class.
What happens if we make toString() method abstract. I tried it and compiler allows to do it ... was wondering if it would have any side effect.
Regards,
Rana Biswas

Similar Messages

  • How  to override toString() method ?

    class  Test
    String x[];
    int c;
    Test(int size)
    x=new String[size];
    c=-1;
    public void addString(String str)
    x=new String
    x[++c]=str;
    public void String toString()
    //  i want to override toString method to view the strings existing in the x[]...
    //   how do i view the strings ?
    //  probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
    //   so i should  RETURN   x[] as an array...but the  toString() method return  type is String not the String array!.
    //   so i am in trouble.
    so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
    i am avoiding println() bcoz of bad design.
    }

    AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
    Test[1] = "some string"
    Test[2] = "some other String"If so, code something like:public String toString() {
        StringBuffer returnValue = new StringBuffer();
        for (int i = 0; i < x.length; i++) {
            returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
        return returnValue.toString();
    } If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
        return java.util.Arrays.asList(this).toString();
    } and call it good. That will print out something like:
    [Some String, another String, null]Depending on what's in your array.
    Good Luck
    Lee

  • Overriding toString method of entrySet() in LinkedHashMap

    Hi all,
    I got a LinkedHashMap which return a Set by entrySet() method. When I print the String represantation of the returned Set, I receive something like [key=value, key=value, key= value]. I, however, would like to override toString method so that I can implement my own representation of the Set class which is returned by entrySet() method. How can I do that if it's possible?

    i believe what Peter was saying was to overrider the Set (in your case...the concrete LinkedhashSet class)
    you're not implementing the add, get, contains, etc..function..you're extending it.
    after extending it..you can overide any public and protected method...any other method not overide is still there for you to use.
    so you would have something like this
    public class MyLinkHashSet extends LinkHashSet{
        public String toString(){
             return a String representation you want 
        public Object getMyObject(){ return myObject; }  // your own method
       // you still have all of the other LinkHashSet methods to use
    }

  • Overriding toString() method

    hello all,
    in the following class how toString() is overriding?
    class Box {
        public Box(){
        public String toString(){
            return "Hello";
        public static void main(String args[]){
            System.out.println(new Box());
    }even though i am not extending anything.
    how the toString() method of String class is overriding here?
    is it due to Object class?
    thanks
    daya

    even though i am not extending anything.
    how the toString() method of String class is
    overriding here?
    is it due to Object class?Yes, thats it exactly. Even when you do not extend and class, by default every class inherits from the Object class. Since toString is defined in the Object class, you override it when you defing toString with the same signature.

  • When and why do we override toString() method

    public class BobTest {
            public static void main (String[] args) {
              Bob f = new Bob("GoBobGo", 19);
              System.out.println(f); // if i put s.o.p("hello"); the overridden toString doesnt get called, y so ?
         class Bob {
            int shoeSize;
            String nickName;
            Bob(String nickName, int shoeSize) {
              this.shoeSize = shoeSize;
              this.nickName = nickName;
            public String toString() {
               return ("I am a Bob, but you can call me " + nickName +
                       ". My shoe size is " + shoeSize);
         }

    masijade. wrote:
    To get a meaningful String representation of your Object.And just to further the point
    @OP: In answer to your original question: almost always.
    I generally don't regard a class as complete until I've implemented toString() -- or, at the very least, displayed it with println() and determined that the default representation is fine.
    Same goes for equals() and hashCode().
    Winston

  • Overiding the toString method

    If I have a method which takes an array of strings as the first argument and a string as the second argument.
    I will compare the string to each index in the passed in array and add the smaller strings to an arraylist.
    firstly to return an ArrayList, what type of method would it be, String?
    Then how is the toString method overridden to print out the ArrayList if the ArrayList could vary depending on the passed in arguments?
    ;)

    Encephalopathic wrote:
    Implode wrote:
    If I want to print out an ArrayList using a for loop, the toString method needs to be overridden?No, not at all. You simply loop through the ArrayList and println each element. Now if the elements are complex objects, then the toString method of the class that the elements are composed of may need a toString override.
    I had to do that with previous examples.Code is worth a thousand words. What do you mean here? Did what?
    Yeah, sorry, I guess I never explained properly. I know how to override toString method, (totally serperate question)but what if the ArrayList was containing object references , and the ArrayList was built depending on arguments passed to a method , how would the toString be overridden then?Again, you would need to have a toString override of the objects held by the ArrayList, not the ArrayList itself.
    For e.g.,
    import java.util.ArrayList;
    import java.util.Random;
    public class MyFoo {
    private String text;
    private int value;
    public MyFoo(String text, int value) {
    super();
    this.text = text;
    this.value = value;
    @Override // here's the necessary toString override
    public String toString() {
    return text + ": " + value;
    public static void main(String[] args) {
    String[] strings = {"Mon", "Tues", "Wed", "Thurs", "Fri"};
    Random random = new Random();
    ArrayList<MyFoo> fooList = new ArrayList<MyFoo>();
    for (String text : strings) {
    fooList.add(new MyFoo(text, random.nextInt(100)));
    // to print out in a for loop:
    for (MyFoo myFoo : fooList) {
    System.out.println(myFoo);
    }Edited by: Encephalopathic on Nov 15, 2009 9:11 AMI did override toString using complex objects in previous examples(university assignments).
    Thanks for the help. Forget the question. It was sidetrack.
    Edited by: Implode on Nov 15, 2009 9:23 AM

  • How convert results to toString method

    Hi All,
    I am facing the problem to display the results in out.println in jsp pages like...
    I thing it must convert to toSting is it right...
    kindly give ur valualbe reply how to convert toString

    >>>
    override the toString() method in the class ofthe
    the object returned by getRepCdrOptType() (classof
    the reference repCdrOptType in your FormBean)
    ram.pl. give more details.....What does getRepCdrOptType() return -
    1. String[] ? (which is what it looks like)
    In which case ur code should be like this
    <%
    String[] optType =
    =  reportsSelectTypeForm.getRepCdrOptType();
    for(int i = 0; i< optType.length ; i++){
    %>
    <%=optType%>
    <%}%>
    2. Object of some class ?? then override the
    the toString() method in the class.
    ram.
    Thanks for your valuable reply but i am in starting of java so now i give the 3 files for u. Give the how i print the original value instance of [Ljava.lang.String;@104e28b. And also I have one more problem.That is i have 5 screens. i store the values in session and print the last page. After click finished button the control comes to first page and again goes to that flow. But i am going to second time the previouse values are displayed(like if  we check one check box. it always checked in second time also..... But i try to solve this problem to give null in reset() in form bean. But the session values r deleted when going to the next page. kindly give ur idea.
    Form Bean
    public class ReportsSelectTypeForm extends ValidatorForm {
         // --------------------------------------------------------- Instance Variables
         private Integer id;
         /** Report Select Type Screen Property */
         private String repSelTypeAll;
         private Integer repSelTypeValue;
         private String repSelTypeDesc;
         private String repSelTypeInd;
         /** Report CDR Options Screen Property */
         private String[] repCdrOptType = {"ISDN","IP"};
         private String[] repCdrOptDir = {"Outbound Direction"};
         private String[] repCdrOptStatus={"Success Status"};
         private String[] repCdrOptAvlFields;
         private String[] repCdrOptSelFields;
    /** ----------------------------------------------- Report Select Type Screen ----------------------------------------------- */
          * Returns the id.
          * @return String
         public Integer getId() {
              return id;
          * Set the id.
          * @param id The id to set
         public void setId(Integer id) {
              this.id = id;
          * Returns the repSelTypeAll.
          * @return String
         public String getRepSelTypeAll() {
              return repSelTypeAll;
          * Set the repSelTypeAll.
          * @param repSelTypeAll The repSelTypeAll to set
         public void setRepSelTypeAll(String repSelTypeAll) {
              this.repSelTypeAll = repSelTypeAll;
          * Returns the repSelTypeValue.
          * @return String
         public Integer getRepSelTypeValue() {
              return repSelTypeValue;
          * Set the repSelTypeValue.
          * @param repSelTypeValue The repSelTypeValue to set
         public void setRepSelTypeValue(Integer repSelTypeValue) {
              this.repSelTypeValue = repSelTypeValue;
          * Returns the repSelTypeDesc.
          * @return String
         public String getRepSelTypeDesc() {
              return repSelTypeDesc;
          * Set the repSelTypeDesc.
          * @param repSelTypeDesc The repSelTypeDesc to set
         public void setRepSelTypeDesc(String repSelTypeDesc) {
              this.repSelTypeDesc = repSelTypeDesc;
          * Returns the repSelTypeInd.
          * @return String
         public String getRepSelTypeInd() {
              return repSelTypeInd;
          * Set the repSelTypeInd.
          * @param repSelTypeInd The repSelTypeInd to set
         public void setRepSelTypeInd(String repSelTypeInd) {
              this.repSelTypeInd = repSelTypeInd;
         /** ----------------------------------------------Reports CDR Options Screen  -------------------------------------------*/
          * Returns the repCdrOptType.
          * @return String
         public String[] getRepCdrOptType() {
              return repCdrOptType;
          * Set the repCdrOptType.
          * @param repCdrOptType The repCdrOptType to set
         public void setRepCdrOptType(String[] repCdrOptType) {
              this.repCdrOptType=repCdrOptType;
          * Returns the repCdrOptDir.
          * @return String
         public String[] getRepCdrOptDir() {
              return repCdrOptDir;
          * Set the repCdrOptDir.
          * @param repCdrOptDir The repCdrOptDir to set
         public void setRepCdrOptDir(String[] repCdrOptDir) {
              this.repCdrOptDir=repCdrOptDir;
          * Returns the repCdrOptStatus.
          * @return String
         public String[] getRepCdrOptStatus() {
              return repCdrOptStatus;
          * Set the repCdrOptStatus.
          * @param repCdrOptStatus The repCdrOptStatus to set
         public void setRepCdrOptStatus(String[] repCdrOptStatus) {
              this.repCdrOptStatus=repCdrOptStatus;
          * Returns the repCdrOptAvlFields.
          * @return String
         public String[] getRepCdrOptAvlFields() {
              return repCdrOptAvlFields;
          * Set the repCdrOptAvlFields.
          * @param repCdrOptAvlFields The repCdrOptAvlFields to set
         public void setRepCdrOptAvlFields(String[] repCdrOptAvlFields) {
              this.repCdrOptAvlFields=repCdrOptAvlFields;
          * Returns the repCdrOptSelFields.
          * @return String
         public String[] getRepCdrOptSelFields() {
              return repCdrOptSelFields;
          * Set the repCdrOptSelFields.
          * @param repCdrOptSelFields The repCdrOptSelFields to set
         public void setRepCdrOptSelFields(String[] repCdrOptSelFields) {
              this.repCdrOptSelFields=repCdrOptSelFields;
    Action Class forward the success
    JSP Page
    <%@ page language="java" import="java.util.*, com.polycom.e100.ui.action.reports.*,com.polycom.e100.ui.form.reports.*"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ page language="java" contentType="text/html" %>
    <jsp:useBean id="clock" class="java.util.Date" />
    <script language="javascript">
         function getsubmitAction(actionValue)
              document.reportsSelectTypeForm.submitAction.value = actionValue;
    </script>
    <html:form action="/action/reports/dumpValues">
    <html:hidden property="submitAction" value=""/>
    <%
         ReportsSelectTypeForm reportsSelectTypeForm = (ReportsSelectTypeForm)session.getAttribute("reportsSelectTypeForm");
    %>
    <table class="form_outer_table">
         <tr>
              <td class="form_header_row">
              <bean:message key="polycom.e100.reports.viewrep.header"/>
              </td>
         </tr>
         <tr>
              <td align="center">
                   <h3><bean:message key="polycom.e100.reports.viewrep.reptype"/></h3>
                   <h5><bean:message key="polycom.e100.reports.viewrep.repname"/></h5>
                   <h5><bean:message key="polycom.e100.reports.viewrep.repdesc"/></h5>
                   <table width="600" border="0">
                        <tr>
                             <td><bean:message key="polycom.e100.reports.viewrep.repstart"/>: <% out.println(reportsSelectTypeForm.getRepSelDateStart());%> </td>
                             <td><bean:message key="polycom.e100.reports.viewrep.repend"/>: <% out.println(reportsSelectTypeForm.getRepSelDateEnd());%></td>
                             <td> </td>
                             <td> </td>
                             <td> </td>
                             <td> </td>
        <td><bean:message key="polycom.e100.reports.viewrep.reptime"/>:<jsp:getProperty name="clock" property="hours" />:<jsp:getProperty name="clock" property="minutes" /> GMT </td>
      </tr>
      <tr>
        <td colspan="7" align="center"><table class="newWizardInner" >
          <tr>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repid"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.reporg"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdt"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdur"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repctype"/></b></td>
            <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repdir"/></b></td>
              <td align="center"><b><bean:message key="polycom.e100.reports.viewrep.repbw"/></b></td>
          </tr>
          <tr>
            <td><% out.println(reportsSelectTypeForm.getId());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSelTypeInd());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSelDateStart());%></td>
            <td> </td>
            <td><% out.println(reportsSelectTypeForm.getRepCdrOptType());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepCdrOptDir());%></td>
            <td><% out.println(reportsSelectTypeForm.getRepSiteOptText());%></td>
          </tr>
             </table></td>
      </tr>
      <tr>
       <td colspan="7"><table class="newBottomTab" >
          <tr><p> </p>
            <td><html:submit property="back" value="<< Back"  style="width:100px" onclick="getsubmitAction('BACK')"/>
              <html:submit property="finished" value="Finished" style="width:100px" onclick="getsubmitAction('NEXT')"/></td>
          </tr>
        </table></td>
        </tr>
    </table>
    <p> </p>
    </td>
    </tr>
    </table>
    </html:form>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • How to override equals method

    The equals method accepts Object as the parameter. When overriding this method we need to downcast the parameter object to the specific. The downcast is not the good idea as it is not the OO. So can anyone please tell me how can we override the equals method without downcasting the parameter object. Thank you.

    For comparing the objects by value overriding the equals method what I did is like this
    public boolean equals(Object o){
        if( o instanceof Book){
            Book b = (Book)o;
            if(this.id == b.id)
                return true;
        return false;
    }But in the above code I have to downcast the object o to the class Book. This downcasting is not a good as it is not Object-Oriented. So what I want to do is avoid the downcasting. So any idea how to do it?

  • How to override ExecuteWithParms method?

    How I can override ExecuteWithParms method?
    as when click on execute button there are many parameters should return result from another table
    as select query from different table, can i do this? and how??

    thanks Timo. this is more detail
    I have two table Fundemental and Emails and I have many search parameters
    so I need to make custom adf search when click on execute search, get result from all search parameters
    so i need to override executeWithParms to change return value when search in pEmail parameter
    to return "ID_NO IN (SELECT PERSON_CODE FROM EMAILS WHERE EMAIL LIKE '%" + getpEmail()  + "%')";

  • How to override truncateToFit method for SuperTabNavigator

    Hi All,
               How to override truncateToFit method for SuperTabNavigator.
    we have editableLabel method for changing the tab name.
    it is dispalying the ... elipse when entered characters grater than the tab width. it is ok.
    but if the entered characters less than the tab width it is also appending the ... elipse.
    i dont want that . how to remove those. i dont want completely truncateToFit option.
    how to override .
    Can any help me regarding this?
    Thanks in Advance
    Raghu.

    Give me a sample codeNo. Read the links provided by Yannix, try it out for yourself, and if you still have a question, post the code you tried.
    db

  • .toString() method is it better to overload or override?

    Whenever I write a class, I make it a practice to override the .toString() method to display the contents of the properties, for logging and debugging purposes. I recently have seen code samples where the .toString() was overloaded: public String toString(String foo){ ...
    I have never run into a problem with over riding toString(). Obviously there isn't an issue overloading it. But It makes me wonder if there is a particular reason not to override? The only thing I can think is that maybe a j2ee container needs to use .toString() and if a serialized bean class is overriden, then it could cause a problem in the container? Or I could see where a debug tool inside an ide might need to use .toString()?
    Is one way better than the other or is it a matter of style?
    Thanks

    With overloading, they might just as well have named toString(String foo) something else like whatever(String foo). It's not a matter of "one way better than the other" nor "style".

  • ToString() method in my User defined Exception...How is it getting called ?

    CustomException.java
    public class CustomException extends Exception
         private int age;
         public CustomException(int age)
         this.age = age;
         public String toString()
         return "this is my exception";
    ExceptionTest.java
    public class ExceptionTest
         static int age=-1;
         public static void main(String args[]) throws Exception
              if(age<0)
              throw new CustomException(age);
    After executing ExceptionTest.java , the result is
    Exception in thread "main" this is my exception at ExceptionTest.main(ExceptionTest.java:8)
    I am just throwing CustomException , to my knowledge only the constructor should run ?
    What i see is message "this is my exception" is within the toString() method - which i never called.
    From where is the toString() method getting called ?
    Also ,
    If I want an object of my class to be thrown as an exception object, what should I do?

    Your main method is defined as throwing Exception, so the JVM catches the Exception (since nothing in your code does). And it does the equivalent of e.printStackTrace() which, among other things, outputs the result of toString().

  • ...is not abstract and does not override abstract method compare

    Why am I getting the above compile error when I am very clearly overriding abstract method compare (ditto abstract method compareTo)? Here is my code -- which was presented 1.5 code and I'm trying to retrofit to 1.4 -- followed by the complete compile time error. Thanks in advance for your help (even though I'm sure this is an easy question for you experts):
    import java.util.*;
       This program sorts a set of item by comparing
       their descriptions.
    public class TreeSetTest
       public static void main(String[] args)
          SortedSet parts = new TreeSet();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(parts);
          SortedSet sortByDescription = new TreeSet(new
             Comparator()
                public int compare(Item a, Item b)   // LINE CAUSING THE ERROR
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
                   return descrA.compareTo(descrB);
          sortByDescription.addAll(parts);
          System.out.println(sortByDescription);
       An item with a description and a part number.
    class Item implements Comparable     
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       public Item(String aDescription, int aPartNumber)
          description = aDescription;
          partNumber = aPartNumber;
          Gets the description of this item.
          @return the description
       public String getDescription()
          return description;
       public String toString()
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       public boolean equals(Object otherObject)
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       public int hashCode()
          return 13 * description.hashCode() + 17 * partNumber;
       public int compareTo(Item other)   // OTHER LINE CAUSING THE ERROR
          return partNumber - other.partNumber;
       private String description;
       private int partNumber;
    }Compiler error:
    TreeSetTest.java:25: <anonymous TreeSetTest$1> is not abstract and does not over
    ride abstract method compare(java.lang.Object,java.lang.Object) in java.util.Com
    parator
                public int compare(Item a, Item b)
                           ^
    TreeSetTest.java:41: Item is not abstract and does not override abstract method
    compareTo(java.lang.Object) in java.lang.Comparable
    class Item implements Comparable
    ^
    2 errors

    According to the book I'm reading, if you merely take
    out the generic from the code, it should compile and
    run in v1.4 (assuming, of course, that the class
    exists in 1.4). I don't know what book you are reading but that's certainly incorrect or incomplete at least. I've manually retrofitted code to 1.4, and you'll be inserting casts as well as replacing type references with Object (or the erased type, to be more precise).
    These interfaces do exist in 1.4, and
    without the generics.Exactly. Which means compareTo takes an Object, and you should change your overriding method accordingly.
    But this raises a new question: how does my 1.4
    compiler know anything about generics? It doesn't and it can't. As the compiler is telling you, those interfaces expect Object. Think about it, you want to implement one interface which declares a method argument type of Object, in several classes, each with a different type. Obviously all of those are not valid overrides.

  • Plz help.... toString() method

    hi....i came accross this sample of toString method. I was wondering how do i return all the variables instead of dont concat ?Pleas help...
    class ToStringClass {
    String firstName;
    String lastName;
    public ToStringClass(String fname, String lname) {
    this.firstName = fname;
    this.lastName = lname;
    // Override the toString() method
    public String toString() {
    return lastName + ", " + firstName;
    }

    sorry for the misleading question... here is the simple full coding of it
    public class ToStringObjectExample {
        public static void main(String[] args) {
               // Overriding the equals() method
            ToStringClass tsc2 = new ToStringClass("Jane", "Doe");
            System.out.println("Class with toString() method    : " + tsc2);
    class ToStringClass {
        String firstName;
        String lastName;
        public ToStringClass(String fname, String lname) {
            this.firstName = fname;
            this.lastName = lname;
        // Override the toString() method
        public String toString() {
            return lastName + ", " + firstName;
    }the output will be display like :-
    Class with toString() method    : Doe, JaneI was thinking how do i display or print the output directly like below :-
    Doe
    Jane
    , which means that displaying the value of each variable. how do i do the return statement?

Maybe you are looking for