【问题标题】:Having trouble implementing Vector.sort() on my Vector在我的 Vector 上实现 Vector.sort() 时遇到问题
【发布时间】: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() 使用指定的Comparatorsort(Comparator)

标签: java list sorting vector comparable


【解决方案1】:

谢谢你的建议,我已经做到了。我会写下如何以防万一有人遇到我同样的问题。

首先,我使用了 ArrayList 而不是 Vector。 我已经在我的 Animal 类中实现了 Comparable。 我写了我的 compareTo(Animal other) 方法。 我叫 Collections.sort(animals)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多