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

Similar Messages

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

  • 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

  • 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

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

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

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

  • Using mutator and accessor methods in main.

    Would somebody explain to me exactly how mutator and accessor methods make a class and it's driver program work together. I understand the principle of encapsulation, but I'm obviously missing something. I get the syntax, but what actually happens? I'm hoping a fresh perspective on it will help me understand better.
    I guess another way to ask the question could be: how do you use accessor and mutator methods in the main program that calls them?

    >
    the assignment says to have a
    "reasonable set of accessor and mutator methods
    whether or not you use them". So in my case I have
    them written in the class but do not call them inthe
    driver program. And like I said, the program does
    what it's supposed to do.This class you're in worries me. I'm sure what
    polytropos said is true: they're trying to make you
    think about reuse. But adding to an API without cause
    is widely considered to be a mistake, and there are
    those who are strongly opposed to accessors/mutators
    (or worse, direct field access) on OOP design grounds.The class is based on the book Java: Introduction to Computer Science and Progamming, by Walter Savitch. Until now I've been pretty happy with it. Another problem, to me anyway, is that so far we've done a few, cumulative programming projects per chapter. This time, there was one assignment for the whole chapter that is suppsoed to incorporate everything. But that's just me complaining.
    Here is the code I have and that it looks like I'll be turning in... criticisms welcome.
    Here is the class:
    public class GradeProgram//open class
         private double quiz1;
         private double quiz2;
         private double mid;
         private double fin;
         private double finalGrade;
         private char letterGrade;
         public void readInput()//open readInput object
              do
                   System.out.println("Enter the total points for quiz one.");
                   quiz1 = SavitchIn.readLineInt();
                   System.out.println("Enter the total points for quiz two.");
                   quiz2 = SavitchIn.readLineInt();
                   System.out.println("Enter the mid term score.");
                   mid = SavitchIn.readLineInt();
                   System.out.println("Enter final exam score.");
                   fin = SavitchIn.readLineInt();
                   if ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0))
                   System.out.println("Quiz scores are between one and ten.  Re-enter scores");
                   if ((mid>100)||(fin>100)||(mid<0)||(fin<0))
                   System.out.println("Exam scores are between zero and one hundred.  Re-enter scores.");
              while ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0)||(mid>100)||(fin>100)||(mid<0)||(fin<0));
         }//end readInput object
         public void output()//open output object
              System.out.println();
              System.out.println("You entered:");
              System.out.println("Quiz 1: " + (int)quiz1);
              System.out.println("Quiz 2: " + (int)quiz2);
              System.out.println("Mid term: " + (int)mid);
              System.out.println("Final exam: " + (int)fin);
              System.out.println();
              System.out.println("Final grade: " + (int)percent() + "%");
              System.out.println("Letter grade: " + letterGrade());
         }//end output object
         public void set(double newQuiz1, double newQuiz2, double newMid, double newFin, double newFinalGrade, char newLetterGrade)
              if ((newQuiz1 >= 0)&&(newQuiz1 <= 10))
              quiz1 = newQuiz1;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newQuiz2 >= 0)&&(newQuiz2 <= 10))
              quiz2 = newQuiz2;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newMid >= 0)&&(newMid <= 100))
              mid = newMid;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              if ((newFin >= 0)&&(newFin <= 100))
              fin = newFin;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              letterGrade = newLetterGrade;
         public double getQuiz1()
              return quiz1;
         public double getQuiz2()
              return quiz2;
         public double getMid()
              return mid;
         public double getFin()
              return fin;
         public char getLetterGrade()
              return letterGrade;
         private double finalPercent()//open finalPercent object
              double quizPercent = (((quiz1 + quiz2) /2) * 10) / 4;
              if (((((quiz1 + quiz2) /2) * 10) % 4) >= 5)
                   quizPercent++;
              double midPercent = mid / 4;
              if ((mid % 4) >= 5)
                   midPercent++;
              double finPercent = fin / 2;
              if ((fin % 2) >= 5)
                   finPercent++;
              finalGrade = (quizPercent + midPercent + finPercent);
              return (finalGrade);
         }//end final percent object
         private double percent()//open percent object - helping object
              double percentGrade = finalPercent();
              return (percentGrade);
         }//end percent object
         private char letterGrade()//open letterGrade object
              double letter = percent();
              if (letter >= 90)
                   return ('A');
              else if (letter >= 80)
                   return ('B');
              else if (letter >= 70)
                   return ('C');
              else if (letter >= 60)
                   return ('D');
              else
                   return ('F');
         }//end letterGrade object
         private double quizScore()//open quizScore object
              double quizes = ((quiz1 + quiz2) /2) * 10;
              return (quizes);
         }// close quizScore object
    }//end classAnd here is the driver program:
    public class GradeProgramDemo
         public static void main(String[] args)
              String cont;
              do
                   GradeProgram firstStudent = new GradeProgram();
                   firstStudent.readInput();
                   firstStudent.output();
                   System.out.println();
                   System.out.println("Enter more student grades?  Enter Y to continue");
                   System.out.println("or press enter to quit.");
                   cont = SavitchIn.readLine();
                   System.out.println();
              while (cont.equalsIgnoreCase("y"));

  • 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

  • How equals and hashCode fail here?

    I have a set of Address objects. The pair of equals and hashCode are generated by Eclipse as the following:
         @Override
         public int hashCode() {
              final int prime = 31;
              int result = super.hashCode();
              result = prime * result + ((city == null) ? 0 : city.hashCode());
              result = prime * result
                        + ((cityCode == null) ? 0 : cityCode.hashCode());
              result = prime * result + ((country == null) ? 0 : country.hashCode());
              result = prime * result + ((entry == null) ? 0 : entry.hashCode());
              result = prime * result + ((number == null) ? 0 : number.hashCode());
              result = prime * result + ((phone == null) ? 0 : phone.hashCode());
              result = prime * result
                        + ((postalCode == null) ? 0 : postalCode.hashCode());
              result = prime * result
                        + ((province == null) ? 0 : province.hashCode());
              result = prime * result + ((street == null) ? 0 : street.hashCode());
              return result;
         /* (non-Javadoc)
          * @see java.lang.Object#equals(java.lang.Object)
         @Override
         public boolean equals(Object obj) {
              if (this == obj)
                   return true;
              if (!super.equals(obj))
                   return false;
              if (getClass() != obj.getClass())
                   return false;
              final AddressEntity other = (AddressEntity) obj;
              if (city == null) {
                   if (other.city != null)
                        return false;
              } else if (!city.equals(other.city))
                   return false;
              if (cityCode == null) {
                   if (other.cityCode != null)
                        return false;
              } else if (!cityCode.equals(other.cityCode))
                   return false;
              if (country == null) {
                   if (other.country != null)
                        return false;
              } else if (!country.equals(other.country))
                   return false;
              if (entry == null) {
                   if (other.entry != null)
                        return false;
              } else if (!entry.equals(other.entry))
                   return false;
              if (number == null) {
                   if (other.number != null)
                        return false;
              } else if (!number.equals(other.number))
                   return false;
              if (phone == null) {
                   if (other.phone != null)
                        return false;
              } else if (!phone.equals(other.phone))
                   return false;
              if (postalCode == null) {
                   if (other.postalCode != null)
                        return false;
              } else if (!postalCode.equals(other.postalCode))
                   return false;
              if (province == null) {
                   if (other.province != null)
                        return false;
              } else if (!province.equals(other.province))
                   return false;
              if (street == null) {
                   if (other.street != null)
                        return false;
              } else if (!street.equals(other.street))
                   return false;
              return true;
         }But, the following code fails on the removing an Address object
              boolean found = false;
              for(Address ae : entry.getAddresses()){
                   if((int)ae.getId() == aId){
              if(!entry.removeAddress(address))
                   logger.error("Fail to remove address with ID: " + address.getId());
                        found = true;
                        break;

    warnerja wrote:
    The removeAddress method is implemented as the following:
              address.setEntry(null);
              return addresses.remove(address);
    So you set the entry property to null (and presumably it wasn't null beforehand), and then invoke remove with that object. Well, since entry is one of the properties included in the criteria for equality, don't you see a problem with that? It can't find an object "equal" to that one, since the only ones it finds don't match ALL of the fields included in the equality criteria anymore, since you just wiped out one of them on the target object to find.
    Here's another thing that looks suspect:
    for(Address ae : entry.getAddresses()){
    if(!entry.removeAddress( address ))
    ...Note the bolded parts. Anything strike you as odd?warnerja spotted my careless code. I shouldn't have address.setEntry(null); before the removal. After one attribute is changed, the object definitely is not the same again.
    BTW, sorry for little bit messy on the sample code. I put together code from various classes to illustrate the problem.

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

  • How to refresh table display using slis and 'reuse_alv_grid_display method.

    hello,
    how to refresh table display using slis and 'reuse_alv_grid_display method'.
    when i'm refreshing table display it performs once again reuse_alv_grid_display.and when i back the previous value appear.how to solve it?
    neon

    are you chaning any value in the gird if so use this..
    Pass the user_command form name to the Import parameter
    I_CALL_BACK_USERCOMMAND .
    and have the Dynamic form implementation..
    FORM user_command USING ucomm TYPE sy-ucomm
                selfield TYPE slis_selfield.
    "The below is important for Editable Grid.
      DATA: gd_repid LIKE sy-repid, "Exists
      ref_grid TYPE REF TO cl_gui_alv_grid.
      IF ref_grid IS INITIAL.
        CALL FUNCTION 'GET_GLOBALS_FROM_SLVC_FULLSCR'
          IMPORTING
            e_grid = ref_grid.
      ENDIF.
      IF NOT ref_grid IS INITIAL.
        CALL METHOD ref_grid->check_changed_data .
      ENDIF.
      CASE ucomm.
        WHEN 'REFRSH'.
      ENDCASE.
           selfield-refresh = 'X'.
    ENDFORM.                    "user_command

  • 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

  • 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

  • Class HashSet and hashCode method

    I'm using a HashSet class with elements of class A.
    I define the equals method but when i add a object which is already in the set, this object is duplicate.
    Do i have to define the hashCode method in the class A? If yes, i don't understand why this method is used when adding a object.
    Can you give me a explanation ?

    Yes, you do. The hashCode method is used by HashSet and HashMap to find an object. See the API doc for Object, which explains the relationship between equals and hashCode.

Maybe you are looking for

  • "Unable to establish a connection between WebEx and the mail server."

    Hi, I installed Cisco WebEx and integrated with our Microsoft exchange server.  It showed server "UP".  everything's came up and working fine after that and sudenlly i found this message "Unable to establish a connection with the mail server.  Please

  • How can i find the apple id that was used to purchase a computer?

    Someone else in our company purchased a MacBook Air online. He said that when he went through the purchasing process he selected 'Guest' and didn't create an Apple ID. He used a company credit card to pay, which *may* have had an Apple ID associated

  • IDOC to file scenario testing error --

    Hi experts , When doing an IDOC to file scenario the status of the IDOC in XI (the Trace section @  SXMB_MONITOR) shows that PARTY &SERVICE NOT DEFINED the failure occurs at message splitting stage . more details : the sender is represented as a busi

  • Under the column firld value new variable needs to be displayed in

    hi i ahve a query presently in sap script output in main window these three fields are coming i want to add a new line ie bar code for the field value which is coming below it example present output number  item    total amount       unitvalue 001   

  • NON-AIR allowLoadBytesCodeExecution - Converting ByteArray to SWF/MovieClip

    Hello everyone, is there any way to convert a ByteArray (obviously containing a loaded swf's data) to an SWF/MovieClip at runtime in Flash Player 10? Even a very complicated byte-by-byte conversion? There is a very easy solution for this in AIR, that