Equals and ==

Hi all
Please let me know similarities and differences between equals() method and '==' operator. Is their any good example or tutorials regarding this. Please help me. Thanks in advance.
Regards
Rakesh

The == is a basic operator of the core Java language. It lets you compare variables and constants of the same type (both primitive and reference) for equality.
The equals method is defined in Object, the universal superclass of all classes, so equals will be inherited by each and every class.
class AnyClass {
AnyClass c1 = new AnyClass();
AnyClass c2 = c1;
if (c1 == c2) { // case 1
if (c1.equals(c2)) { // case 2
}Case 1 and 2 above actually perform exactly the same test (both cases are true). BUT equals can be overridden in a subclass to mean something else, so you always will have to look in the class documentation to know what it does in that particular case. If you change AnyClass above to,
class AnyClass {
   public boolean equals(Object o) {
       return false;
}now case 1 will still be true because the reference variables are still the same, but case 2 will be false because equals has been overridden to always return false.

Similar Messages

  • Date Filtering With Equals and Time in Interactive Reports

    Using Apex 4.2.0.00.27
    I have a date column in an Interactive Report. The default column and action menu filters include things like "in the last 2 hours". If I remove the time component of the date this fails to find any records.
    If I leave the time component in the date then the user also has the option (via action->filter menu) to select a filter for "equals" and then this fails to find any records.
    I would like to keep the time component but also allow the filter for "equals a specific date".
    Greg

    adamt wrote:
    Thank you very much fac586!
    It's probably obvious I'm not very familiar with APEX (not HTML/CSS!) but managed to figure out a place to put what you said...If you are unfamiliar with the web technologies used in APEX, spend some time on the tutorials here: start with HTML, then XHTML, CSS, Javascript and the HTML DOM, and now HTML5.
    I appended the following in the template definition section for "Region without Buttons and Titles" and the Interactive Report looks how the users want now! I should probably take a copy of that template and only use it for the relevant IRs so that nothing else gets messed up.There are 3 ways to include CSS in web pages. The easiest is using an internal style sheet as you've done, but where you've put it is <a href="https://forums.oracle.com/forums/thread.jspa?messageID=10178616&#10178616">invalid according to the HTML specification</a>. The page HTML Header property in the APEX Page Attributes is the appropriate place for such style sheets. However ff you want to apply these styles globally across your application then that's not a scalable approach as it involves modifying every page with an IR. The standards-compliant approach is to modify the required page templates, either to include an external style sheet containing these overrides, or (more ambitiously and efficiently) copying and modifying the theme files in a different location and changing the page templates to reference them.
    <style type="text/css">
    .apexir_WORKSHEET_DATA th div {
    margin-left: 0;
    .apexir_WORKSHEET_DATA th,
    .apexir_WORKSHEET_DATA td {
    border: 1px solid #CCCCCC;
    </style>Always post code wrapped in tags<tt>\...\</tt> tags to preserve formatting and special characters.

  • Problem in not overriding equals and Hashcode

    I have a very small question. We know that if we do not override the equals and hascode of Object class, we can not use the object in the Hashed collection. Can anybody provide me a concrete example which indicates the problem if we do not override the equals and hascode.

    back to the original question from DebadattaMishra
    I have a very small question. We know that if we do
    not override the equals and hascode of Object class,
    we can not use the object in the Hashed collection.
    Can anybody provide me a concrete example which
    indicates the problem if we do not override the
    equals and hascode.lets extend the example from jverd. Suppose we have a Person and want to store some Score in a HashMapclass Person {
        String name;
        Person(String name) {
            this.name = name;
    class Score {
        int value;
        Score(int value) {
            this.value = value;
    public class PersonTest {
        Map<Person, Score> map = new HashMap<Person, Score>();
        void test() {
            map.put(new Person("John"), new Score(1));
            map.put(new Person("Maria"), new Score(2));
            Score score = searchScore("John");
            System.out.println("Found: " + score);  // Found: null
        Score searchScore(String name) {
            return map.get(new Person(name));
    }if you run test() you will get "Found: null" since the John instance in the HashMap is not the same as used in searchScore. HashMap uses the equals method from Object since we have not overridden it.
    If we add an equals methodclass Person {
        String name;
        Person(String name) {
            this.name = name;
        public boolean equals(Object obj) {
            if(obj instanceof Person) {
                Person p = (Person) obj;
                return name.equals(p.name);
            } else {
                return false;
        // hashcode not overridden
    }we probably will get "Found: null" most if the time. The HashMap uses the hashcode() to create an index for saving the keys, so it mostly will not find the Person.((there is still a very small probability that the correct Person is found))
    It will work fine if we add a hashcode like    public int hashCode() {
            return name.hashCode();
        }I hope this example helped.

  • Adding Objects To a HashSet, overriding equals and hashCode

    Hi everyone,
    I'm trying to add objects to a HashSet, using a string identifier (an attribute of these objects) to determine if two objects are equal.
    I have a class 'IntExpEvent' class that overrides the equals and hashCode methods.
    public class IntExpEvent implements ExperimentalEvent{
    public int correctAnswer;
    public String identifier;
    public IntExpEvent(String id, int correctAnswer){
         this.identifier = id;
         this.correctAnswer=correctAnswer;
    public String getID(){
         return(this.identifier);
    public boolean equals(ExperimentalEvent e){
         return (this.identifier.equals(e.getID()));
    public int hashCode(){
         System.out.println((this.getID()).hashCode());
         return (this.getID()).hashCode();
    private int hashCode=-1;
    public int hashCode() {
         if(hashCode==-1) {
         char[] ca=getID().toCharArray();
         for(int x=0;x<ca.length;x++) {
              hashCode+=ca[x];
         return(hashCode);
         IntExpEvent e1 = new IntExpEvent("test_IntExpEvent",4);
         IntExpEvent e2 = new IntExpEvent("test_IntExpEvent",6);
         HashSet hs = new HashSet();
         System.out.println(hs.add(e1));
         System.out.println(hs.add(e2));
    I can still add both e1 and e2 to the HashSet, which is what I'm trying to stop from happening. i.e. objects with the same identifier should be treated as the same object, allowing only one to be added to the HashSet. Does anyone know how I can do this? Help would be greatly appreciated

    In fact you don't override the equals method. The signature defined in the Object class is
      boolean equals(Object o)In your case it is
      boolean equals(ExperimentalEvent e)So instead of overriding the method you're overloading it.
    Regards

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

  • Overrideing equals() and hashCode()

    This is related to my previous post. I have followed the advice that was given to me. I overrode equals() and hashcode()
    public class TwoTuple<A,B>{
         public final A first;
         public final B second;
         public TwoTuple(A a, B b){
              first = a;
              second = b;
         public boolean equals(TwoTuple tt){
            return first.equals(tt.first);
         public int hashCode(){
              return 31 * first.hashCode();
         public String toString(){
              return "Variable == " + first + "  Value == " + second;
    }Test class:
    import java.util.*;
    public class Test{
         private static Set<TwoTuple> state = new HashSet<TwoTuple>();
         public static void main(String[] args){
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              for(TwoTuple tt : state){
                   System.out.println(tt);
              TwoTuple tt = new TwoTuple("Testing", true);
              System.out.println("Equals == " + tt.equals(new TwoTuple("Testing", true)));
              System.out.println("Equals == " + tt.equals(new TwoTuple("Hello", true)));
              System.out.println("Equals == " + tt.equals(new TwoTuple("abc", true)));
    }Output;
    Variable == Testing  Value == true
    Variable == Testing  Value == true
    Variable == Testing  Value == true
    Equals == true
    Equals == false
    Equals == falseI am still getting 3 elements that are identical inside my set. What am I doing wrong?

    SquareBox wrote:
    This is related to my previous post.An unrelated piece of advice that I was going to put in your previous thread (but it seems you've moved on):
    Be careful how you name your classes.
    'TwoTuple' may mean something to you, but it's not very descriptive to the rest of us. Furthermore, the word 'Tuple' suggests a very specific usage that isn't borne out in any of the methods you've implemented. What about 'Pair' or 'Couple' or 'Duo'? (In the world of names, shortest is usually best.)
    Winston

  • How does CEF perform equal and unequal cost load balancing?

    hello
    How does CEF perform equal and unequal cost load balancing?
    thanks

    Hello Wang,
    it is only EIGRP that can perform load balancing over unequal cost links.
    For equal cost links CEF allocates 16 buckets and maps them to the the physical links.
    the result of a binary operation is used to associated a packet to an outgoing interface:
    Source IP address EXOR DEstination IP Address EXOR hash
    the hash is a seed that changes only at every reload.
    Actually the last 4 bits are used so that each flow can be classified in one bucket.
    then the outgoing interface is the one asscociated to the result of the exor operation.
    Another way to see is that m bits are used so that 2^m is equal to N number of links (if N is even)
    the rule is simple and pre-established
    Hope to help
    Giuseppe

  • Overriding equals and hashCode

    Everywhere I look it talks about overriding equals and hashCode together, and it also warns that doing it wrong could complicate things severly. However I haven't been able to find good documentation on how to do it properly.
    Any suggestions on where to find this out, or how to properly override the two?

    Thank you!!
    I have to say I have been very impressed with this forum. I have posted on many java forums recently with little or no success. This forum has been great, I normally get responses if a few minutes and they are all very helpful.
    thanks again

  • Comparator question - changing Equals and HashCode too?

    Hi all I have an object test - this contains 2 variables:
    Int a; and Int b;Then there is a method called test() which returns a double and looks like this:
    public Double test()
    return a * (1d / b);
    }I have implemented the compareTo method do the "compareTo" test using the call to test() not on the fields directly e.g.
    this.test().compareTo(anotherObject.test()) instead of
    if (this.a != null && anotherDateInterval.a != null)
                compareTo = this.a.compareTo(anotherDateInterval.a);
            }Because I using the test() in the compareTo do I need to change the equals and hashcode method as well to reflect the use of test()?
    e.g.
    public boolean equals(Object obj)
       if (test() == null)
                if (other.test() != null)
                    return false;
            else if (!test().equals(other.test()))
                return false;
    }

    That depends if there are any class invarients that can be depended upon.
    The basic rule is that if .equals() returns true, then .compareTo() must return 0, but not necessarily the other way around. As long as this holds true, you don't really have to change .equals() or .hashCode(). If you're still using the identity equals method, then you probably don't have to worry about it. If you've overridden .equals() to be dependent upon a and b in some way, you probably do have to change the way .equals() works to make sure that .equals() doesn't return true if .compareTo() doesn't return 0.
    - Adam

  • HashSet - equals and hashCode

    I must be missing the obvious over here..from what I understood of HashSet's/equals and hashCode, the program below should not add the Person object twice. Please suggest whats wrong...
    import java.util.*;
    public class TestHashSet2 {
    Set set = null;
    public TestHashSet2() {
    set = new HashSet();
    class Person {
    String name;
    Person(String name) {
    this.name = name;
    public boolean equals(Person person) {
    if (name.equals(person.name)) {
         return true;
    } else {
         return false;
    public int hashCode() {
    int code = name.length();
    System.out.println(" HashCode: " + code);
    return code;
    public void addPerson() {
    Person person1 = new Person("Mike");
    set.add(person1);
    Person person2 = new Person("Mike");
    System.out.println(" person1 equals person2: " + person1.equals(person2));
    set.add(person2);
    public void showPersons() {
    Iterator iterator = set.iterator();
    Object obj = null;
    while (iterator.hasNext()) {
    obj = iterator.next();
    System.out.println(" ELEMENT--> " + obj);
    System.out.println(" Number of elements in set: " + set.size());
    public static void main(String args[]) {
    TestHashSet2 tSet = new TestHashSet2();
    tSet.addPerson();
    tSet.showPersons();
    }

    the method equals(Person) has a different parameter type as equals(Object) and therefore doesn't override it. You need to change the method to equals(Object). This is a common 'gotcha' ...

  • Why Collection interface declares equals() and hashCode() method

    When I went through the source code of Collection interface, I found equals() and hashCode() are declared? Why? If a class implements this interface, it will inherit these two method from Object, and we can true to override them.

    It's probably so that they can provide the documentation that you see there.

  • Equals and serialized copy

    I have an container that can contains any kinds of other objects and I ignore their nature. The only restriction I put is that those object must be Serializable.
    I have implmeneted a clone() method that make a deep copy with serialization. (See http://developer.java.sun.com/developer/JDCTechTips/2001/tt0410.html )
    Now I want to be able to compare the two objects with equals (and with hashcode). Can I use the serialized value of my object to test the equality? I means return true iff the serialized byte[] contains the same bytes, and computes a hashCode from the serialized byte array?
    Asked otherwise, do we have the garantee of the next assertion:
    equal (this.serialize().serialize() , this.serialize())where serialize and equal are
    class A
        private synchronized byte[] serialize()
            ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            byte[] result = baos.toByteArray();
            oos.close();
            return result;
        private static equal(byte[] a, byte[] b)
            if (a.length!=b.length) return false;
            for (int i=0;i<a.length;i++) if (a!=b[i]) return false;
    return true;

    Let's forget the problem transient field and asume the
    those fields are not used in the equality comparison.
    I thing I have found a case were it will not work.
    Imagine that the object I serialize is a B-Tree. I
    imagine that even if two objects are equals, it's
    possible that they have two differents tree structure
    and thus a 'naive' serialization will give two
    different byte[].
    Very true. I would not go as far as call it 'naive', rather an efficient serialization would cause this as the tree structure would be traversed differently.
    I'm I wrigth or does it exist a specification that
    impose something like
    a.equals(b) <=> equal(a.serialize(),b.serialize())?No, there is nothing in any specification that imposes that the serialized version of the objects byte-stream is equal if their equals method returns true. I could change the serialVersionUID without changing any other class and your byte-stream would differ, even though the internal structure is retained. Serialization is just to serialize objects and to have a way to read them back into objects again.
    That was why I asked the initial question, which was why you need this functionality? yes, I am still curious
    Regards,
    Peter Norell

  • WebLogic 10.3 doesn't implements equals() and hashCode() for TimerHandle?

    Hi,
    I'm using WebLogic 10.3 and need to use TimerHandle to handle some logic in my application.
    Below is a scenario.
    At the time by creating EJB Timer, I've saved the TimerHandle for later use into Database along with specific name as a key.
    Then, at the time to execute/awaken timer I need to check that the saved TimerHandle is the same as passed Timer.
    @Timeout
    public void execute( final Timer timer )
    // getting key from passed object in timer.getInfo().
    // getting saved timerhandle by key. let's say dao.getXxxHandle(key);
    // perform checking.
    if ( timerHandle != null && timerHandle.equals( timer.getHandle() ) )
    // do sth.
    else
    //do another thing.
    The result is always drop in else block.
    By doing this is working on WAS7 and JBoss4xx (getting to if block). I was wondering if WebLogic doesn't implements equals and hashCode method then is there another way to check that the retrieved TimerHandle is the same one as timer.getHandle()?
    I'm thinking of adding some unique ID to see if timehandle is the same one or not? However as I mentioned, It works on WAS and JBoss. Does WebLogic has another way to handle my scenario?
    Any help would be appreciate.
    Thanks in advance,
    Nattachai W.

    As you have suggested, it looks like we don't override the equals() method on either our local or clustered TimerHandle implementations.
    We opened a bug (9558396) so we can address it in a future patchset.
    In the meantime, if you have an Oracle support contract, you could open a service request and ask for a patch for bug 9558396 to be created.
    -steve-

  • Comparing dynamic fields of objects using equals and hashCode methods

    To compare the different objects of the same class with their contents like jobTitleId, classificationId, deptId & classificationId was to be done and do some manipulations later using Set and Map. I was able to do that by simply overriding the equals and hashCode methods of Object class and was able to fetch the information (like in the following Map).
        Map<LocationData, List<LocationData>>
    The following is the class I used (its been shown to you so that it can be referred for my problem statement):
    LocationData class
        package com.astreait.bulkloader;
        public class LocationData {    
            String locId, deptId, jobTitleId, classificationId;
            @Override  
            public boolean equals(Object obj) {        
                LocationData ld = (LocationData)obj;       
                return this.deptId.equals(ld.deptId) && this.jobTitleId.equals(ld.jobTitleId) && this.classificationId.equals(ld.classificationId) &&
        this.locId.equals(ld.locId);   
            @Override  
            public int hashCode() {        
                return deptId.hashCode() + jobTitleId.hashCode() + classificationId.hashCode() +locId.hashCode();  
    Problem:
    I'm already known to which all fields of this object I need to make the comparison.
    i.e I'm bound to use the variables named classificationId, deptId, jobTitleId & locId etc.
    Need:
    I need to customize this logic such that the fields Names (classificationId, deptId, jobTitleId & locId etc) can be pulled dynamically along with their values. So, as far as my understanding I made use of 2 classes (TableClass and ColWithData) such that the List of ColWithData is there in TableClass object.
    I'm thinking what if I override the same two methods `equals() & hashCode();`
    such that the same can be achieved.
        TableClass class #1
        class TableClass{
            List<ColWithData> cwdList;
            @Override
            public boolean equals(Object obj) {
                boolean returnVal = false;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be compared
                return returnVal;
            @Override
            public int hashCode() {
                int returnVal = 0;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be found for their individual hashCodes
                return returnVal;
    ColWithData class #2
        class ColWithData{
            String col; // here the jobTitleId, classificationId, deptId, locId or any other more fields info can come.
            String data; // The corresponding data or value for each jobTitleId, classificationId, deptId, locId or any other more fields.
    Please let me know if I'm proceeding in the right direction or I should make some any other approach. If it is ok to use the current approach then what should be performed in the equals and hashCode methods?
    Finally I need to make the map as: (Its not the concern how I will make, but can be considered as my desired result from this logic)
        Map<TableClass, List<TableClass>> finalMap;

    Hello,
    What is the relation with the Oracle Forms tool ?
    Francois

  • Implementing equals() and hashcode

    Hi,
    I need to implement equals() and hashcode() in a class. I only need to use one class variable in the equals() method; String id.
    I'm having difficulties to understand the examples I've seen - can someone please help me out?
    regards, Puzz

    And I know you said you had a hard time understanding some examples, but I'm not sure which examples you've seen. Here is some recommended reading that I think explains this concept well:
    Sun's Java Tutorial: The equals and hashCode Methods
    Josh Bloch: Effective Java
    JavaWorld: Implementing equals and hashCode
    IBM: Defining hashCode() and equals() effectively and correctly
    JavaPractices: Implementing hashCode
    JavaWorld: override hashcode/equals
    ~

  • What's the difference between equals() and compareTo() method

    I'm confused between the two method from String class ,,, what's the main difference between equals() and compareTo() method?

    API docs give quite clear information IMHO
    public boolean equals(Object anObject)
    Compares this string to the specified object. The result is true if and only if the argument is not null and is
    a String object that represents the same sequence of characters as this object.
    public int compareTo(String anotherString)
    Compares two strings lexicographically. ....
    The result is a negative integer if this String object lexicographically precedes the argument string. The
    result is a positive integer if this String object lexicographically follows the argument string. The result is
    zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return
    true. Mike

Maybe you are looking for