Symantec Interview Question
Principal Software EngineersCountry: United States
Depending on the parameter which are required for comparing the Objects(CAT and DOG in this case). Equals can be manipulated to see what we wish it to see:) . .
Code: -
import java.util.Arrays;
/*
Q) Sort the array(have to implement the equals method in Cat and Dog).
Cat c = new Cat("Snow Ball");
Dog d = new Dog("Max");
array = {c, d, ... };
*/
class Dog implements Comparable<Object> {
String name;
// other dog attributes
// Only Constructor
Dog(String name) {
this.name = name;
}
@Override
public boolean equals(Object otherObj) {
if (otherObj instanceof Dog || otherObj instanceof Cat) {
// can compare other common attributes if required
return name.equals(otherObj.toString());
}
return false;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(Object otherObj) {
if (otherObj instanceof Dog || otherObj instanceof Cat) {
return name.compareTo(otherObj.toString());
}
throw new RuntimeException("Only works for Cats and Dogs Class.");
}
}
class Cat implements Comparable<Object> {
String name;
// other cat attributes
// Only Constructor
Cat(String name) {
this.name = name;
}
@Override
public boolean equals(Object otherObj) {
if (otherObj instanceof Dog || otherObj instanceof Cat) {
// can compare other common attributes if required
return name.equals(otherObj.toString());
}
return false;
}
@Override
public int compareTo(Object otherObj) {
if (otherObj instanceof Dog || otherObj instanceof Cat) {
return name.compareTo(otherObj.toString());
}
throw new RuntimeException("Only works for Cats and Dogs Class.");
}
@Override
public String toString() {
return name;
}
}
public class Main {
public static void main(String arg[]) {
Object[] pets = { new Dog("Max"), new Cat("Snow Ball"),
new Dog("Brownie"), new Cat("Not so Brownie") };
System.out.println("\nBefore Sorting:\n");
displayHouse(pets);
Arrays.sort(pets);
System.out.println("\nAfter Sorting:\n");
displayHouse(pets);
}
private static void displayHouse(Object[] pets) {
for (Object pet : pets) {
System.out.println(pet);
}
}
}
Before Sorting:
- trish August 17, 2013Max
Snow Ball
Brownie
Not so Brownie
After Sorting:
Brownie
Max
Not so Brownie
Snow Ball