0

I am studying some example code that enrol customer into a service, and the method below checks if the customer has that type of service. I assume that if we want to compare to objects, i.e. service, we need to use equals() method.

However the code below (in customer class) works perfectly fine, but it did't work after I changed == to equals.() Can someone help to explain why it behave like this? Is it because under some circumstances we need check equality using ==? Many thanks!

boolean hasService(Service sd) { //Service is a class that has int, String and ArrayList as variable
    boolean hasService = false;
    for (int i=0; i<.length; ++i) { //
        //doesn't work if change to ((serviceAvailable[i] ).equals(pd)), why? 
          if (serviceAvailable[i]==sd) //serviceAvailable is an Array stores different services
            hasService = true;
    }
    return hasService; 
}

The class Service is as below:

 class Serivce {
    private String name;
    private int price;
    private ArrayList <Customers> customersErolled;
  //geters and setters methods

  boolean equals (Serive a){
    if (this.paperName.equals(a.paperName)&&a.semester==this.semester&& a.year==this.year&&a.studentsEnrolled.equals(this.studentsEnrolled) ){
        return true;
    }else{
        return false;
    }
  • You have to *override* `equals` to make it work as desired. It is possible that the default definition, which is exactly the same as using `==` (except issues with `null`-values), already works for you. – Marko Topolnik Oct 02 '14 at 09:59
  • 1
    This depends on the implementation of the class `Service`. Without further information your question cannot be answered. – Uwe Plonus Oct 02 '14 at 10:00
  • I understand that == checks if they are the same object, but what confuses me is that in here Service is an object, and I thought we should use equals. But on the contrary == works – stillAFanOfTheSimpsons Oct 02 '14 at 10:02
  • You probably have defined equals() in the Service class in a wrong way. Show us the code of the class – Giovanni Oct 02 '14 at 10:05
  • @UwePlonus I 've added the service class. Hope it gives more information – stillAFanOfTheSimpsons Oct 02 '14 at 10:07
  • Are you sure che Service class you're using is the right one? You may be importing another Service class from another package. Check the imports in your java file. – Giovanni Oct 02 '14 at 10:14
  • @Giovanni Thanks! I've added the equals method I defined in Service class. – stillAFanOfTheSimpsons Oct 02 '14 at 10:20
  • The pasted `equals()` method can never be the coreect implementation to your class as it cannot compile. Also the correct `equals()` method has the signature `public boolean equals(Object)`. – Uwe Plonus Oct 02 '14 at 10:23
  • Your equals implementation should have signature public boolean equals(Object other). Also add the annotation Override so you will be sure that you are overriding the correct method. – Juru Oct 02 '14 at 10:28
  • @juru I tried with public boolean equals (Object other), and if (this.paperName.equals(other.paperName)&&...but it won't compile as there something wrong with other.paperName. Any ideas? Thank you! – stillAFanOfTheSimpsons Oct 02 '14 at 10:34
  • 1
    You will need to cast other to the Service class like this: this.paperName.equals(((Service) other).paperName). The equals method is not class specific, hence the parameter of type Object. At the beginning of your equals method you should actually do if(!(other instanceof Service)){ return false; } because any class that is not Service should not be equal to something of type service. – Juru Oct 02 '14 at 10:35
  • Here's an idea: learn Java basics by going through introductory material. No need to ask the StackOveflow community about each and every detail you don't yet know. – Marko Topolnik Oct 02 '14 at 10:35

1 Answers1

1

The equality operator == will compare the object references, while equals will depend on the implementation of equals on the object that you are comparing. By default this will compare the hash of the object (which is unique for each object in the jvm that your code runs in at that moment). For a propper equals you need to override the equals method in Service and compare the instance variables there one by one (or whathever kind of equality you want / need).

Juru
  • 1,623
  • 17
  • 43
  • The odd thing is that the Service ad passed to hasService method can't be the same thing as the Service stored in the customer's service array right? so I don't understand how come the code can compile and run.. – stillAFanOfTheSimpsons Oct 02 '14 at 10:22
  • It could, I don't know where your array comes from or how it is constructed. – Juru Oct 02 '14 at 10:28
  • The array is a field in the Customer class, and the method hasService is also defined in the Customer class – stillAFanOfTheSimpsons Oct 02 '14 at 10:37
  • 1
    Also if you defined the strings as string literals(this means like this: String s = "hello") then two strings with the same string literal would share the same space in the common pool, this is an optimization of java to preserve memory. – Juru Oct 03 '14 at 20:40
  • 1
    Following code would output "true, false, false": public class HelloWorld{ public static void main(String []args){ String s1 = "Hello"; String s2 = "Hello"; String s3 = new String("Hello"); String s4 = new String(new char[] {'H', 'e', 'l', 'l', 'o'}); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1 == s4); } } – Juru Oct 03 '14 at 20:45