看,.equalsIgnoreCase logic
与 Dog 一起工作绝对没问题,但不像你那样。这是你需要做的。
比方说你想说2 dogs are same if they have same Name
。
然后修改你的 Dog 类,如下所示:
public class Dog implements Comparable<Dog> {
private String name;
private double age;
private double weight;
public Dog(String name, double age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public int compareTo(Dog anotherDogToCompare) {
return this.getName().toLowerCase().compareTo(anotherDogToCompare.getName().toLowerCase());
}
}
现在,无论何时,你想比较 2 只狗,compareTo
如果上面给出了,0
那么 2 只狗是相同的,否则不一样。请注意,如果它们具有相同的名称,我假设 2 只狗是相同的。
如果这不是平等标准,则无需担心。compareTo
您只需要根据您的逻辑更改内部代码即可。阅读更多
好的。现在您的代码将是:
public static int findDog(String toFind, ArrayList<Dog> dogs)
{
for (int i = 0 ; i < dogs.size() ; i++)
{
if (dogs.get(i).compareTo(toFind) == 0) // Only this changes
{
return i;
}
}
return -1;
}