Does the following code use the hashCode
method of my Scooter
class:
void using_ArrayList(){
List coll=new ArrayList();
Scooter s1=new Scooter();
s1.setNumber("HR26KC345352344");
s1.setHorse_power(123.321);
s1.setYear_of_made(1997);
Scooter s2=new Scooter();
s2.setNumber("HR26KC34535");
s2.setHorse_power(123.321);
s2.setYear_of_made(1997);
Scooter s3=new Scooter();
s3.setNumber("HR26KC345352344");
s3.setHorse_power(123.321);
s3.setYear_of_made(1997);
coll.add(s1);
coll.add(s2);
coll.add(s3);
Scooter s=new Scooter();
s.setNumber("HR26KC345352344");
System.out.println(coll.contains(s));
}
Scooter Class:
class Scooter{
private String number;
private double horse_power;
private int year_of_made;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public double getHorse_power() {
return horse_power;
}
public void setHorse_power(double horse_power) {
this.horse_power = horse_power;
}
public int getYear_of_made() {
return year_of_made;
}
public void setYear_of_made(int year_of_made) {
this.year_of_made = year_of_made;
}
public boolean equals(Object o){
if((o instanceof Scooter)&&((Scooter)o).getNumber()==this.getNumber()){
System.out.println("EQUALS:TRUE"); //OK
return true;
}
else{
System.out.println("EQUALS:FALSE"); //OK
return false;
}
}
public int hashCode(){
System.out.println("HASHCODE");// NOT able To reach here...
return number.length();
}
}
I am able to reach equals()
method. But not able to reach hashCode()
method. Does hashCode()
method is NOT used by ArrayList
collection? Please tell me, as I am new to Java-Collections.
Unlike, say, a HashMap, an ArrayList does not need to use the hashCode() method since the order of the elements in an ArrayList is determined by the order in which they were inserted, and not by hashing.