Fix the equals and hashCode methods so that sets work as expected

master
DjBushido 2014-01-22 15:17:45 -05:00
parent 57dfd938fa
commit 8b893cd06a
2 changed files with 26 additions and 5 deletions

View File

@ -41,10 +41,10 @@ public class PartTwo {
reader.close();
} catch (FileNotFoundException e) {
System.out.println("Could not open file: " + filename);
System.err.println("Could not open file: " + filename);
return;
} catch (IOException e) {
System.out.println("Error reading the CSV file.");
System.err.println("Error reading the CSV file.");
return;
}
@ -61,7 +61,7 @@ public class PartTwo {
writer.close();
} catch (IOException e) {
System.err.println("Error writing unique vehicles to CSV");
System.err.println("Error writing unique vehicles to CSV.\n" + e.getMessage());
// Don't return here, we can still complete the rest of the program
}

View File

@ -64,8 +64,8 @@ public class Vehicle {
}
public String toCSV() {
return this.modelYear + this.manufacturerName + this.modelName +
this.horsePower + this.noCylinders + this.noGears;
return this.modelYear + "," + this.manufacturerName + "," + this.modelName + "," +
this.horsePower + "," + this.noCylinders + "," + this.noGears;
}
public String toString() {
@ -73,4 +73,25 @@ public class Vehicle {
" Model Name: " + this.modelName + " Horsepower: " + this.horsePower +
" No. Cylinders: " + this.noCylinders + " No. Gears: " + this.noGears;
}
// Need to implement both equals() and hashCode() for guaranteeing unique Sets
// http://stackoverflow.com/questions/16238182/hashset-contains-duplicate-entries
// Also:
// http://www.coderanch.com/t/572755/java-programmer-SCJP/certification/HashSet-adding-duplicates-hashcode-obects
@Override
public boolean equals(Object _v2) {
Vehicle v2 = (Vehicle) _v2;
return ((this.modelYear == v2.modelYear) &&
(this.manufacturerName.equals(v2.manufacturerName)) &&
(this.modelName.equals(v2.modelName)) &&
(this.horsePower == v2.horsePower) &&
(this.noCylinders == v2.noCylinders) &&
(this.noGears == v2.noGears));
}
@Override
public int hashCode() {
return this.modelYear + this.manufacturerName.hashCode() + this.modelName.hashCode() +
this.horsePower + this.noCylinders + this.noGears;
}
}