【发布时间】:2023-03-31 08:52:01
【问题描述】:
我知道这是一件小事,但我仍然无法弄清楚如何在我的 Vector 上实现 sort() 函数。 我将粘贴我目前正在处理的示例:它是动物园(即动物向量)
类动物园:
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);
}
}
类动物:
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());
}
}
我的问题是:我需要什么 sort() 方法才能工作? 我试过了:
-使 Animal 类实现 Comparable(因此,编写了我的 compareTo(Animal other) 函数)
-让 Animal 类实现 Comparator(因此,我自己编写了 comprare(Animal a, Animal b) 函数)
我不断收到的错误是:
the method sort(Comparator<?Super Animal> in the type Vector<Animal>
is not applicable for the arguments.
如果我使用 ArrayList 而不是 Vector,我会得到什么不同吗? (我在使用矢量,因为我在学校被教导使用它,我知道它并不是最新鲜的课程)
【问题讨论】:
-
Would I get anything different if I were using ArrayList instead of Vector心意,一个可能不比你老的java类,很多东西!对于那些,有Collections#sort -
实施
Comparable并阅读界面文档以确保您遵守所有规则。你没有“实现”Comparator,这个独立于你的类。此外,不推荐使用 Vector,您应该改用 ArrayList。 -
如果集合的元素是
Comparable,您可以使用不带参数的sort()或使用指定的Comparator和sort(Comparator)
标签: java list sorting vector comparable