Method equals(Object anObject)

What are the essential differences between
String test = "some string";
"some string".equals(test);and
String test = "some string";
test.equals("some string");Are there any reasons to prefer one over the other?

In your specific example there is no difference. In general, if the variable test is not null, there is no difference. If the variable test is null, the the latter will throw a NullPointerException.

Similar Messages

  • Why methods equals() and hashCode() is defined in Object Class?

    Why methods equals() and hashCode() is defined in Object Class?

    If you have two objects and you don't know (or care about) their exact types, but you still want to know if they are the same, then you can do something like this:
    Object o1 = getObject1();
    Object o2 = getObject2();
    if (o1.equals(o2)) {
      // they are the same, do something
    } else {
      // they are different, do something else
    }This could be useful if you were to write a generic cache, for example.
    A similar thing is true for hashCode(), if you want to manage things in a HashSet, you'll need them to implement hashCode().
    If Object didn't have those methods, then you'd have to write that code against a more specific interface/class and it wouldn't be so general any more.

  • String equal method Vs Object equal method.

    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.

    RGEO wrote:
    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.Because "equal" means different things for different objects. For a String, "equal" would mean that both Strings being compared have the exact same characters, in the same sequence. For an Integer, "equals" would mean that both objects have the same integer value.

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

  • Method "equals" not implemented for class "Pan1"

    Method "equals" not implemented for class "Pan1" -- this is the error I'm getting while running one static Analyzer. Can anybody say, what is this error , and how to rectify it ?

    The static analyzer may have noticed that either you may invoke .equals() on instances of this class (possibly through polymorphism) and you have not implemented the method in your class. This is most likely a warning since many times lack of an implemented .equals() method in such cicumstances will lead to Object.equals() being executed and that simply checks to see if the object references are the same - quite a bit stronger than what one would probably expect from .equals();
    it is also possible that you did implement an equals() method but that you used the wrong argument type. This is a common mistake:
    public boolean equals(MyClass other) {
       return /* something */;
    }This type of warning may be ignored, or if it troubles you and there is no way to disable it for the classes that you know you have implemented correctly, you might consider adding an equals method of the form:
    public boolean equals(Object other) {
       return super.equals(other);
    }Chuck

  • Avoiding Bugs with equals(Object)

    Hey, guys!
    I've got a quick question. I've been diving through a new code base, lately, and I put a static analysis tool against it, and ran into a couple places where the code was using String.equals to compare one object that was a String, and another object that wasn't.
    For example, the code looked like this:
    expectedString.equals(actualObject);When it should have looked like this:
    expectedString.equals(actualObject.aMethodThatProducesAString());It was human error, but the root of the problem was human error, but the compiler didn't complain, because java.lang.Object.equals accepts and object, and therefore, any class that is a subclass of java.lang.Object must also accept any type of Object. I brought it to the attention of a colleague to understand what the code was supposed to be doing. He felt that this really ought to raise a compiler error somehow, to prevent these mistakes. He suggested creating a static method of some sort that only accepts Strings, to do the comparison, and then have any other calls within our codebase that use equals(Object) fail at compile time. The only reasonable way I could think to do this without too much effort would be to use something like AspectJ to declare the method call illegal. But AspectJ doesn't play nicely with many of the other tools we are using.
    Personally, this is the first time I've seen this become an issue, so I'm not sure it's really a big deal to just use a static analysis tool every once in a while to find stuff like that, but I wondered if anybody else had faced this problem in the past, and found some reasonable way to overcome it?
    Thanks!
    - Adam

    He felt that this really ought to raise a compiler error somehow, to prevent these mistakes. Per the API definition, it was legal usage (I think someone else mentioned this, but it's important to repeat).
    He suggested creating a static method of some sort that only accepts Strings, to do the comparison, Or even better, use the pre-written one from [Jakarta Commons|http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#equals(java.lang.String,%20java.lang.String)]. This has the added benefit of being null-safe.
    Personally, this is the first time I've seen this become an issue, so I'm not sure it's really a big deal to just use a static analysis tool every once in a while to find stuff like that, but I wondered if anybody else had faced this problem in the past, and found some reasonable way to overcome it?Good programming habits, and reliance on libraries of useful methods.
    I'd suggest taking a day or two, grepping for every use of equals(), and replacing it. Then yell at people if they don't continue the practice.

  • Integer.equals(Object) acting flakey in JDK/JRE 1.5

    I am having a problem with java.lang.Integer.equals(Object).
    Here's the code:
    class Address
    Integer id;
    // Other fields...
    class AddressDTO
    Integer id;
    // Other fields...
    // Remove all Address Domain objects that are not represented in the UserDTO's address map.
    l1: for(Address address : user.getAddresses().toArray(new Address[0]))
    for(AddressDTO addressDTO : userDTO.getAdderssDTOs().values())
    if(address.getId().equals(addressDTO.getId()))
    continue l1;
    user.removeAdderss(address);
    My problem is, when address.id is 13 and addressDTO.id is 13, address.getId().equals(addressDTO.getId()) returns false when it should return true.
    I watched this happen, even stepped through it with my Eclispe debugger, several times. I stepped into the Integer.equals(Object arg0) method, and verified that this.value=13 and arg0.value=13.
    Then, I asked a coworker to come see it, and as I stepped through the code, for probably the 10th time, address.getId().equals(addressDTO.getId()) returned true as it should instead of false as it had the previous 9 times.
    Can anyone tell me why or how this could happened?
    Has anyone else witnessed this kind of behavior?

    This thread might explain it:
    http://forum.java.sun.com/thread.jspa?threadID=5221311
    Are you using new Integer(value) somewhere?  You should be using compareTo rather than equals because equals will be checking that they are the same object reference rather than comparing their values. The caching mechanism of values from -128 to 127 could be causing this behavior.
    Hmm, upon further review looks like equals is overridden. That is bizarre.
    Edited by: Outtascope on Sep 29, 2007 10:42 AM

  • Adivce on implementing boolean equals(Object)

    Given that SomeClass extends Object and is is not part of an overly complicated hierarchy where each subclass adds some data useful to identify its instances.
    Which version is better and why?
    public boolean equals(Object o){
        return (o != null
            && this.id != null
            && this.getClass().equals(o.getClass())
            && this.id.equals(((SomeClass) o).id))
        || super.equals();
    public boolean equals(Object o){
        return (o != null
            && this.id != null
            && o instanceof SomeClass
            && this.id.equals(((SomeClass) o).id))
        || super.equals();
    }

    So your question is about instanceof vs. comparing the results of getClass, right?
    It depends on the semantics of your hierarchy.
    The contract of equals says it has to be symmetric. a.equals(b) must return the same result as b.equals(a).
    class Super {
    class Sub extends Super {
    Super super = new Super();
    Sub sub = new Sub();
    boolean b1 = super.equals(sub);
    boolean b2 = sub.equals(super); If you use instanceof, then super's equals must be final, or else Sub's equals must only check for instance of Super, not instanceof Sub. If Super checks for instanceof Super, and Sub checks for instanceof Sub, then b1 (super.equals(sub)) can be true (since sub is an instance of Super) but b2 (sub.equals(super)) can never be true.
    If you look at the collections hierarchy, you'll see that the equals methods check for instanceof the interface. For instance (HA!), two Lists are equal iff they both implement List, and they have the same elements in the same order. So ArrayList, LinkedList, and any custom List that you might implement must check instanceof List, not instanceof ArrayList, etc.
    The general rule is, if you're going to use instanceof, then to preserve symmetry, all classes in the subtree must check for instanceof the same class (or interface), and it has to be at the highest (closest to Object) level in the subtree of classes that could be equal to each other.
    Does that make sense?
    ¶

  • Interfaces and methods of Object class

    JSL 2.0 states the following
    If an interface has no direct superinterfaces, then the interface implicitly
    declares a public abstract member method m with signature s, return type r,
    and throws clause t corresponding to each public instance method m with
    signature s, return type r, and throws clause t declared in Object, unless a
    method with the same signature, same return type, and a compatible throws
    clause is explicitly declared by the interface.
    But the following codes produces empty output
    package test;
    import java.lang.reflect.Method;
    public class TestIterface {
        public static void main(String [] args){
            Method [] methods=Y.class.getMethods();
            for(int i=0, n=methods.length;i<n;i++)
                System.out.println(methods);
    interface Y{
    What are the reasons of such behaviour?

    then the interface implicitly declares a public abstract member method
    "Implicit" means that it's implied that the interface declares those methods; unlike java.lang.Object, there is no interface from which all other interfaces descend. All interfaces at the "top" of the inheritance hierarchy are implied to expose at least the same methods as Object.
    Hope this helps...

  • SAP workflow -SAP error WL210 -Error triggering default method for object &

    Hi Experts,
    User is encountered with the error message "Error triggering default method for object &" when he is performing approval action in SES workitem .
    Could you please advise me how to avoid this issue.
    Thanks in advance for your valuable help.
    Rajani
    Edited by: Rajani SAPABAP on Sep 13, 2011 4:50 PM

    Hi Rajani,
    I think that it's an authorization issue.
    Please check if u find which authorization object is violated in SU53.
    Regards,
    Asit

  • ERROR TRIGGERING DEFAULT METHOD FOR OBJECT (INCOMING INVOICE).

    When trying to open invoices in my ERP inbox to authorise I get the following message.
    ERROR TRIGGERING DEFAULT METHOD FOR OBJECT (INCOMING INVOICE).
    . There might be an authorisation issue. but i am not confirm.
    I have checked the authorisation in SU53 also.
    is it possible that there is some other reason for it.
    If so then what are they?
    please help.

    Hi Naval,
            Is it a custom business object....make sure that the status of all object components are set to Implemented or released..and  regenerate the Object...
    Thanks
    Srinivas

  • Why do we use cl_gui_cfw= flush method in Object Oriented ALV programming

    Dear Friends,
    Please solve my query regarding control framework. Why do we use cl_gui_cfw=>flush method in Object Oriented ALV programming. I studied and found that this method transfers automation queue to Front end.  But I could not find any further update on this.
    Thanks & Regards
    Amit Sharma

    Generally this is to restrict the traffic b/w frontend and backend. This means that every operation in Control Framework should be first buffered in the backend and synchronized with the frontend at certain points (one of this point is calling synchronization method cl_gui_cfw=>flush ). This explicit order of synchronization is due to RFC call needed for every communication b/w front/back end. So to avoid to many RFC calls we do it only at certain time.
    Please refer [Automation Queue|http://help.sap.com/saphelp_wp/helpdata/en/9b/d080ba9fc111d2bd68080009b4534c/frameset.htm]. I think it explains the concept quite well.
    Regards
    Marcin

  • XL Reporter Error. (Open Workbook) Method '~' of object '~' failed. 64-bits

    Hello, good morning.
    Checking the Desktop System Platforms
    https://websmp208.sap-ag.de/~form/sapnet?_SHORTKEY=01100035870000706510&_SCENARIO=01100035870000000183&_ADDINC=011000358700001192682007E&
    I have installed 2007A SP01 PL13 in a 2008Server with SQL2008 but xl reporter not works in the cliente platforms with Windows 7 Prof 64 bits and Office 2010 Profesional installed in 32-bit version:
    The message: Error al inicial excel. Causa: (Open Workbook) Method '' of object '' failed
    Checked:
    Notes: 1077263, 898635, 918188, 1287193
    Threads:
    COM Add-in Program Required to run XL Reporter
    XL Reporter - Report Organizer cannot load
    Error while opening XL reporter
    XL Reporter Startup failed
    XL Report unable to load with Excel 2010
    I put a message to SAP Business One Global Support Centre, but the result is:
    "The MS Office 2010 x64 is not supported. Please refer to the supported platforms landing page".
    In teh landing page says: " (6) For the time being, the SAP Business One release tracks 2007 and 8.8 only support the 32-bit version of the Microsoft Office 2010 editions."
    ¿Any idea?
    Thanks

    Hi,
    Checkk
    http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91?prof=required
    http://social.technet.microsoft.com/Forums/en-US/office2007deploymentcompatibility/thread/334c9f30-4e27-4904-9e71-abfc65975e23?prof=required)and
    Thanks,

  • DTW - Method of object failed

    Hi
    I'm trying do do an import of AP Credit Notes and getting the error 'Method '' of object '' failed 65171'.
    No matter what I try - can't get past this one. Has anyone seen this before?
    Regards
    Danie

    Hi
    I have the following columns in my
    Header:
    Record Key - 1, 2, 3, ......
    CardCode - V-TRA007......
    Comments - Credit Inv no 6316 .....
    DocCurrency - R
    DocDate 20110125
    DocType - dDocument_Items
    Lines:
    ParentKey - 1, 2, 3,3, 4, 5,5,5, 6.......
    No LineNum as this is new import not update - Although it makes no diff to the error I'm getting
    BaseEntry - which is DocEntry of PCH1 (Although DocNUm and DocEntry are the same in both tables)
    BaseLine - corresponds to the line no's in PCH1
    BaseType - 18
    CostingCode - PC
    ItemCode - SFEE_Accomod
    Price - 171.05
    Quantity - 1
    VatGroup - I0
    Warehouse - FCS-FIND
    Regards
    Danie

Maybe you are looking for

  • Photosho CS Problem - Can't drag a layer set from one document to another one

    I have two documents open On the source document, i want to drag a layer set from this document to a new one, but its not letting me What would cause this. My structure for the source document is >Set 1 Layer Set      >layer      > Adjustment Layer  

  • SSRS Drillthrough Reports functionality not working in exported Excel format

    Hi All, Recently I have made a drillthrough report in SSRS 2008R2,Its working fine only in MSBI run mode and preview mode of report designer.Going from main report to sub report and any other report through drillthrough report its work fine. When I e

  • AnyConnect Client Profile in ASDM

    I am trying to configure a client profile under the AnyConnect Client Profile tab in the ASDM but keep getting an error message stating "Check that you have a proper AnyConnect package installed in the AnyConnect Client Software menu.  Also check tha

  • Trying to run "zsnes-netplay" but it crashes

    Hi. I wanna play SNES games over the network with my friend, though the Network feature is disabled in the newest ZSNES version so I have to install version 1.42. Found this in AUR, and it installed just fine. When I run it though, I get this error:

  • Autounattend.xml not launching from USB stick

    Hi All, I am currently tearing my hair out over this autounattend.xml which I am using as a part of image deployment for company I am working for.  I am currently deploying an image via a USB media and my autounattend.xml is currently in the root of