I'm aware that it's a trivial matter, still I can't figure out how to implement the sort() function on my Vector. I'll paste the example I'm currently working on: it's a Zoo (that is a Vector of animals)
Class Zoo:
import java.util.Vector;
public class Zoo {
//attributes
private Vector<Animal> animals;
//builder
public Zoo() {
animals = new Vector<Animal>();
}
//function that adds an animal to my Zoo
public void addAnimal(Animal a) {
animal.add(a);
}
//function that removes an animal from my Zoo
public void removeAnimal(Animal a) {
animals.remove(animals.indexOf(a));
}
//function that prints a list of animals currently in my Zoo
public void view() {
System.out.println(animals);
}
}
Class Animal:
public class Animal{
//attributes (name and species)
private String name;
private String species;
//setters and getters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
//builder
public Animal(String name, String species) {
this.name = name;
this.species = species;
}
//override of toString from Object class
public String toString() {
return "The animal " + getName() + " belongs to the family of " + getSpecies() + "\n";
}
//override of equals from Object Class
public boolean equals(Object other) {
return other instanceof Animal
&& getName().equals(((Animal)other).getName())
&&getSpecies().equals(((Animal)other).getSpecies());
}
}
My question is: what do I need for the sort() method to work? I've tried:
-Making the Animal class implement Comparable (and, therefore, writing my compareTo(Animal other) function)
-Making the Animal class implement Comparator (and, therefore, writing my own comprare(Animal a, Animal b) function)
the error I keep getting is:
the method sort(Comparator<?Super Animal> in the type Vector<Animal>
is not applicable for the arguments.
Would I get anything different if I were using ArrayList instead of Vector? (I'm using vector since I've been taught to use it in school, I'm aware that it's not exactly the most fresh class out there)