Always override: toString(), clone(), equals(Object obj)?

In classes that I write Is there any reason to not always override:
public String toString();
public boolean equals();
public Object clone(Object obj);Further, why not always provide a default Comparator ?
public Comparator getDefaultComparator();This seems logical?

kakusaretasuna wrote:
thank you.
I am just beginning to learn Java, and so I am making a checklist of things to do when I write a class.
When it makes sense, I will always implement:
toString()
clone()
equals()
getDefaultComparator()getDefaultComparator? No, I wouldn't do that. Where did you get that idea from?
And if you override equals, you should always override hashCode as well, and vice versa.
As a rule, I do not override those methods unless I have a specific reason to.
And, I learned that by default a Java class is not Serializable . Therefore, for each of my
classes, I need to adjust them to safely be Serializable , and then declare them Serializable Only if there's a reason to serialize them. Again, it doesn't make sense for all classes, or even most.
This makes sense to me, however, I don't want to appear foolish to exeperienced developers. For example, I learned that:Worry less about appearing foolish and more about learning. Everybody had to start somewhere, and this stuff is generally not intuitive. Nobody cares if you don't automatically know it all.
>
private final void foo(); // "final" is annoying and foolish?As with most things, there are at least two schools of thought on that. In general, I don't make methods final unless I specifically don't want them overridden. Some people feel you should declare them final by default, and only remove the final in cases where there are specific reasons to override them. Neither is right or wrong. It's mostly a matter of convention, and somewhat a matter of context.
private void foo() { this.privateMethod(); } // "this" is annoying and foolish?I personally hate using "this" when it's not necessary, and it's never necessary in the case of method calls. It doesn't even add any clarity. It's just clutter.
>
I am sure there are many other construts that experienced developers avoid.Yes, but don't worry about learning them all right now.

Similar Messages

  • Method Overriding-toString(),hashCode() and equals()?

    Hi,
    In some Java Classes, I saw that
    toString()
    hashCode()
    equals()
    these 3 methods of Object Class is overloaded.
    I don't understand why and in what situation we have to override these 3 methods of Object Class.
    Thanks in advance for ur Knowledge Sharing.
    Regards,
    S.Prabu

    toString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
    hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
    Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these.

  • Overriding equals(Object o) method

    hi,
    I have a problem in equals method ..returns true always...
    can anyone suggest whats wrong ?
    thanks for the help
    public  boolean equals(Object NumberC)
                if (NumberC == null) return false;
                 if ( NumberC instanceof Counter)
                      Counter myCr = ( Counter) NumberC;
                     if(this.number == (myCr)
                         return true;
                     }//end if
                 } //end if 
                 return false;
             }// end equals
      

    sorry..yes it always returns true
    here's my code again
    public  boolean equals(Object NumberCounter)
                if (NumberCounter == null) return false;
                 if ( NumberCounter instanceof Counter )
                     Counter myCr = ( Counter ) NumberCounter;
                     if(this.number == (myCr.number))
                         return true;
                     }//end if
                 } //end if 
                 return false;
             }// end equals

  • Two equal objects, but different classes?

    When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
    The source codes of the program bind_ref.java are listed as below:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.spi.ObjectFactory;
    import java.util.Hashtable;
    public class bind_ref {
    public static void main( String[] args ) {
    // Set up environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
    env.put( Context.PROVIDER_URL, "file:/daniel/" );
    Context ctx = null;
    File f = null;
    Fruit fruit1 = null, fruit2 = null;
    byte [] b = new byte[10];
    try {
    ctx = new InitialContext( env );
    Hashtable the_env = ctx.getEnvironment();
    Object [] keys = the_env.keySet().toArray();
    int key_sz = keys.length;
    fruit1 = new Fruit( "Orange" );
         SubReference ref1 = fruit1.getReference();
    ctx.rebind( "reference", fruit1 );
         fruit2 = ( Fruit )ctx.lookup( "reference" );
         System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
         System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
         System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
         System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
         System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
         System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
    } catch( Exception ne ) {
    System.err.println( "Exception: " + ne.toString() );
    System.exit( -1 );
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    All the outputs are shown as below:
    =======================================================
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    FruitFactory: obj's class = (class javax.naming.Reference)
    FruitFactory: obj's hashCode = -1759114666
    FruitFactory: obj = (Reference Class Name: Fruit
    Type: fruit
    Content: Orange
    FruitFactory: ( obj instanceof SubReference ) = false
    FruitFactory: subref_class_name = (Fruit)
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    ref1's class = (class SubReference)
    fruit2.myRef's class = (class javax.naming.Reference)
    ( ref1 instanceof SubReference ) = true
    ( fruit2.myRef instanceof SubReference ) = false
    ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
    ref1.equals( fruit2.myRef ) = true
    ========================================================
    I hightlight the critical codes and outputs related to the strangeness with bold texts.
    Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?

    It can also depend on how you implement the equals method.
    class Cat {
        String name;
        Cat(String n) {
            name = n;
    class Dog {
        String name;
        Dog(String n) {
            name = n;
        public boolean equals(Object o) {
            return name.equals(o.name);
        public static void main(String[] args) {
            Dog d = new Dog("Fred");
            Cat c = new Cat("Fred");
            System.out.println(d.equals(c));
    }

  • 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

  • ToString() and equals() HELP!

    Hi, this is my prompt:
    Create an abstract class named Vacation that contains data fields (instance variables)
    ; a string variable; destination and a double variable; budget. Use an overloaded constructor, to allow client to set beginning values for destination and budget. That means the constructor takes two parameters, and calls two mutator methods one allowing the client to set new destination value for the vacation, and the next one to allow the client to set the new budget for the vacation. Furthermore this class contains accessor methods, one for returning the name of the destination of the vacation, and the other for returning the budget of the vacation. The class also holds two more methods, one is a toString( ), to return a string representation of the vacation, and an equals( ) method to compare two Vacation objects for the same vacation field value. Finally, the class has an abstract method that computes how much the vacation is over or under budget. That means returning by how much the vacation is over or under budget.
    I've got this so far:
    public abstract class Vacation
        public String destination;
        public double budget;
        public Vacation()
            destination = "";
            budget = 0;
        public Vacation(String destination, double budget)
            this.destination = destination;
            this.budget = budget;
        public String getDestination()
            return destination;
        public void setDestination(String destination)
            this.destination = destination;
        public double getBudget()
            return budget;
        public void setBudget(double budget)
            this.budget = budget;
        public String toString()
            return destination;
    }could anyone tell me how to write a toString()/equals() method?

    Is this correct??? the original code is on the first
    post...
    also, i'm not sure if my toString() has all the
    return values. I'm kind of confused by the wording of
    the instructions and I don't know what a "string
    representation of a vacation" quite means.It means whatever you want it to mean. You've decided it means the value of the destination field. You did the same in your attempt at overriding the equals method from the Object class, so you're consistent (that's good). But the equals method has the signature public boolean equals(Object o), the parameter type is Object, not String - so you'll need to change that and cast the parameter to be of type String (if that's what you really want - but I would think you'd want to be comparing Vacation objects, not String objects for equality). And I would think (but it's completely up to you) that you'd work the "budget" field's value into these methods somewhere (as suggested in a previous post) but again, it's completely up to you - I think that once you change the equals method signature you'll have satisfied the letter of the requirements.
            public boolean equals(String
    destination)
    if(this.destination.equals(destination))
    return true;
    else
    return false;
    code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • UnsupportedOperationException with List.add(Object obj)

    List statusCodes = Arrays.asList(OcsCustomDicInfo.acctRefundStatusCodes);
              List statusNames = Arrays.asList(OcsCustomDicInfo.acctRefundStatusNames);
              // Add an additional item          statusCodes.add(Integer.toString(statusCodes.size()));           statusNames.add("All");
              String[] statusCodesArray = (String[]) statusCodes.toArray();
              String[] statusNamesArray = (String[]) statusNames.toArray();I used the Arrays.asList to convert an Array(which is String[]) to a List,then add one item to the List with add(Object obj).
    But when the debuger run to the "statusCodes.add(Integer.toString(statusCodes.size())); " breakpoint, it throws UnsupportedOperationException.
    I checked the API, the relative statement is:
    UnsupportedOperationException - if the add method is not supported by this list.
    Why? Doesn't the Arrays.asList() return a "List" Interface,and "List" support "add()" operation,but why not support in this case?

    Sorry,i have made a mistake when posting the code.
    This is the code:
    List statusCodes = Arrays.asList(OcsCustomDicInfo.acctRefundStatusCodes);
    List statusNames = Arrays.asList(OcsCustomDicInfo.acctRefundStatusNames);
    // Add an additional item          
    statusCodes.add(Integer.toString(statusCodes.size()));
    statusNames.add("All");
    String[] statusCodesArray = (String[]) statusCodes.toArray();
    String[] statusNamesArray = (String[]) statusNames.toArray();

  • TreeMap's containsValue(Object obj)

    In the Map interface there is a method called containsValue(Object obj) that returns a boolean. My question is, does this method call the objects equal method? or does it have some other way to check for the object in the map?

         * Returns <tt>true</tt> if this map maps one or more keys to the
         * specified value.  More formally, returns <tt>true</tt> if and only if
         * this map contains at least one mapping to a value <tt>v</tt> such
         * that <tt>(value==null ? v==null : value.equals(v))</tt>.  This
         * operation will probably require time linear in the Map size for most
         * implementations of Map.
         * @param value value whose presence in this Map is to be tested.
         * @return  <tt>true</tt> if a mapping to <tt>value</tt> exists;
         *          <tt>false</tt> otherwise.
         * @since 1.2
        public boolean containsValue(Object value) {
            return (root==null ? false :
                    (value==null ? valueSearchNull(root)
                                 : valueSearchNonNull(root, value)));
        private boolean valueSearchNull(Entry n) {
            if (n.value == null)
                return true;
            // Check left and right subtrees for value
            return (n.left  != null && valueSearchNull(n.left)) ||
                   (n.right != null && valueSearchNull(n.right));
        private boolean valueSearchNonNull(Entry n, Object value) {
            // Check this node for the value
            if (value.equals(n.value))
                return true;
            // Check left and right subtrees for value
            return (n.left  != null && valueSearchNonNull(n.left, value)) ||
                   (n.right != null && valueSearchNonNull(n.right, value));
        }Hope that helps :)

  • Is this write way to clone a object?

    All,
    I this the correct way to clone a object? if not so can anyone point me the right way to do that. Because this method is taking longer time to execute.
    import java.io.*;
    public class ObjectCloner
        public ObjectCloner()
        public static Object clone(Object obj)
            throws Exception
            ByteArrayOutputStream bstream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bstream);
            out.writeObject(obj);
            out.close();
            ByteArrayInputStream binstream = new ByteArrayInputStream(bstream.toByteArray());
            ObjectInputStream oin = new ObjectInputStream(binstream);
            Object newobj = oin.readObject();
            return newobj;
        public static int sizeOf(Object obj)
            try
                ByteArrayOutputStream bstream = new ByteArrayOutputStream();
                ObjectOutputStream out = new ObjectOutputStream(bstream);
                out.writeObject(obj);
                out.close();
                return bstream.toByteArray().length;
            catch(Exception ex)
                ex.printStackTrace();
            return 0;
    }

    calvino_ind wrote:
    i might be wrong, but i think there are some really easier ways to clone an object:
    public class Age {
    int numberOfYears;
    public Age(int numberOfYears) {
    this.numberOfYears = numebrOfYears;
    public Object clone() {
    return new Age(this.numberOfYears);
    No! This is very wrong. For this simple example, all one needs is class Age to implement Cloneable and
    public Object clone() {
             return super.clone();
    }which will automatically give you a shallow clone of the the class.
    Consider what ill happen with your approach when one clones superclasses of class Age.
    Edited by: sabre150 on May 26, 2008 3:42 PM

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

  • Why is getAllEPSystems(Object obj) from ILandscapeService so slow?

    Hi,
    I use getAllEPSystems(Object obj) from ILandscapeService
    ILandscapeService landscapeService = (ILandscapeService) PortalRuntime.getRuntimeResources().getService(ILandscapeService.KEY);
    Enumeration allSapSystems = landscapeService.getAllEPSystems(user).keys();
    It work good but very slow. What can be reason?
    Regard
    Raissa

    Hi Raissa,
      You could have asked this question in the same post where you had asked for the list of all systems.
      Anyway, here are some comments.
      I faced the same problem with listing all the systems. But I overcame the same with some other workaround.
      1. I wrote a service which will synchronize all the systems defined into an XML file in KM.
      2. I then read this XML file from KM in the custom application to list the systems to the end user.
      This will always be much faster.
      Try the same.
    Regards,
    JP

  • Overriding attributes in ABAP objects

    Hello,
    I currently want know if it is possible to override attributes in ABAP objects. i know it is possible with methods. I have extend a previous class functionality and want to change the refrence type of an attribute from the parent class, but only on the child. Is this possible in ABAP object or even in normal object oriented techniques.
    Thanks
    Brendan

    Hi,
    ususally you can achive this with other technics. You can e.g. use the class hierarchy for this:
    The attribute is of type REF_SUPERCLASS. Within the superclass it should be working when you set subclasses of REF_SUPERCLASS as attribute.
    Another way is to use interfaces as reference type for your attribute.
    Please refer to [ABAP Objects|http://help.sap.com/saphelp_nw70/helpdata/EN/ce/b518b6513611d194a50000e8353423/frameset.htm]. Especially the chapters about Inheritance and Interfaces.
    Regards Rudi

  • 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

  • [svn:fx-3.x] 9493: Applying patch (SDK-22435) submitted by Aaron Boushley which updates ObjectUtil to use toXMLString rather than toString for XML objects .

    Revision: 9493
    Author:   [email protected]
    Date:     2009-08-23 16:09:56 -0700 (Sun, 23 Aug 2009)
    Log Message:
    Applying patch (SDK-22435) submitted by Aaron Boushley which updates ObjectUtil to use toXMLString rather than toString for XML objects.
    QE notes:  None
    Doc notes: None
    Bugs: SDK-13919
    Reviewer: N/A
    Tests run: Checkin
    Is noteworthy for integration: No
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-22435
        http://bugs.adobe.com/jira/browse/SDK-13919
    Modified Paths:
        flex/sdk/branches/3.x/frameworks/projects/framework/src/mx/utils/ObjectUtil.as

  • Clone an Object

    Hey everyone,
    I just had a question about cloning an object.
    I have an object and within that object there is a field that holds a "date".
    I want to clone the object x number of times (x is user input) and each clone the "date" is the next day.
    So the second clone's "date" value would be the next day after the first clone's "date" value. I also want each clone stored into an array of that object.
    I have a date class and within that date class is a method called "nextDay" which changes the date to the next day.
    I hope that makes sense.
    Anyways, the way I went about it was this:
    Object original = new Object();
    drawCount = user input;
    Object[] array = new Object[drawCount];
    array[0] = original;
    if(drawCountInt > 1)
         for(int j = 1;j <= drawCountInt;j++)
            Object daClone = (Object) original.clone;
            daClone.date = daClone.date.nextDay();
    }Now that seems like it would work once.
    I am trying to figure out, how would I increment the date in a loop?
    I could not figure out a way to use the counter to maybe make the nextDay happen more often.
    I could not also find a way to make a clone of a clone inside a loop and just use the nextDay on that.
    How would I make a clone off the latest clone inside a for or while loop?
    Sorry if any of this seems a little unclear. Feel free to ask questions of course.

    So something like this then?
    if(drawCountInt > 1)
    {     Array[1] = (Object) original.clone;
             for(int j = 1;j <= drawCount;j++)
                       Array[j] = (Objectt) Array[j].clone;
                       Array[j].date = Array[j].date.nextDay();
    }

Maybe you are looking for

  • Validation on items in Hide/Show Region

    I have a validation on an item that is in a hide/show region. I display all my errors in-line with the field. When the validations fires, after the page is submitted, the hid/show region is closed so the user can't see the error. Is there a way in th

  • Who will implement jdbc api interface?

    Hi Friends, I have One doubt on jdbc api interface, I will Explait it clearly Through java if we want connect any database we need to use JDBC, To conne to database, We need to load the driver and we need to establish the connection and we need to ex

  • Any way to trim line ends?

    I used the shape builder tool in CS5 to "trim" the blue lines as they overlapped the rectangle boundary.  Is there a better way to trim the lines so that the ends of the lines but up to the border rectangle?  Any other ideas how to accomplish the sam

  • Ipad 2 will not sync edited photos from iphoto

    I've changed some of my photos to black and white or sepia in iphoto.  When I sync them to my ipad 2, they remain in color.  Any ideas?  It's only happened to pictures edited within the past month or so.  Wondering if it coincides with a recent iphot

  • Having problems  performing field mappings

    Hi Experts... I am trying map  werks field to another field of the same type . However we are suppose to map the last two characters of source work field. The source incoming data for werk can have 2 ,3 or 4 characters. I have tried various combinati