Interview Question
Software TraineesCountry: India
Interview Type: In-Person
class A{
int i;
A(){
this.i=0;
}
A(int i){
this.i=i;
}
public String toString(){
return "i="+i;
}
}
public class Manager1{
public static void main(String [] args){
A a1=new A(10);
A a2=new A(10);
A a3=a1;
System.out.println(a1);
System.out.println(a2);
System.out.println(a1==a2);
System.out.println(a1.i==a2.i);
System.out.println(a1.equals(a2));
System.out.println(a1.equals(a3));
System.out.println((new A()).equals(new A()));
}
}
is it like that.???
You can implement Comparable or use a Comparator. Following is an example where we want to compare two accounts based on balance.
public class Account implements Comparable<Account>{
@Override
public int compareTo(Account account) {
return (this.balance < account.balance ) ? -1: (this.balance > account.balance ) ? 1:0 ;
}
}
public class AccountBalanceComparator implements Comparator<Account>{
@Override
public int compare(Account accountA, Account accountB) {
return (accountA.getBalance() < accountB.getBalance() ) ? -1: (accountA.getBalance() > accountB.getBalance() ) ? 1:0 ;
}
}
You must override hashcode method, whenever you override equals method, as the best practice (though your program will get compiled & run, even without this). May be that's what the interviewer was expecting to hear back, as part of response to this question.
- ruharish October 25, 2013