-3
import java.util.*;
class emp{
    String city;
    String name;
    emp(String a, String b)
    {
        city=a;
        name=b;
    }
}
public class HelloWorld{

     public static void main(String []args){
         Set<emp> s = new HashSet<emp>();
         emp s1=new emp("bangalore","mukesh");
         emp s2= new emp("bangalore","mukesh");
         s.add(s1);
         s.add(s2);
         System.out.println(s1.equals(s2));
         System.out.println("finsih");
         System.out.println(s);

     }
}

i am creating two objects, which are same but they get entered in set and why s1.equals(s2) return false?

Mukesh Gupta
  • 101
  • 1
  • 1
  • 6
  • 1
    You need to write your own equals function by overriding the equals function of object class ,if you want these two objects to be equal. – bit-shashank Jun 18 '18 at 04:02
  • If it was your intention that the set only have one `emp` object (because you consider them equal), then you need to implement both `equals()` and `hashCode()`. See [Understanding the workings of equals and hashCode in a HashMap](https://stackoverflow.com/q/1894377/5221149). – Andreas Jun 18 '18 at 04:06
  • 1
    *FYI:* Java naming convention is for class names to start with uppercase letter, i.e. `Emp`. Also, naming the parameters `a` and `b` is not very helpful to people calling the method. – Andreas Jun 18 '18 at 04:07

2 Answers2

-1

It has nothing to do with inserting to set. You need to override equals, for example below is the basic equal method :

@Override
public boolean equals(Object o) {

    if (o == this) return true;
    if (!(o instanceof Emp)) {
        return false;
    }
    Emp emp = (Emp) o;
    return  Objects.equals(city, emp.city) &&
            Objects.equals(name, emp.name);
}

Follow details , follow the sample here: https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

Rudy
  • 7,008
  • 12
  • 50
  • 85
-1

Since you have not overridden equals(), Object#equals is used which by default uses == operator. Since you have created 2 objects with new operator, their refernces are different and hence call to equals() returns false. You can override both equals and hashcode to provide equality:

class emp{
    String city;
    String name;
    emp(String a, String b) {
        city=a;
        name=b;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof emp)) return false;
        emp test = (emp) o; 
        return Objects.equals(city, emp.city) &&
                Objects.equals(name, emp.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(city, name);

}

Now attempting to store the objects will store only one object in the set.

Prashant
  • 4,775
  • 3
  • 28
  • 47