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