[英]how to compare arraylist with String whilst ignoring capitalization?
我收到一个错误消息,说对于Dog
类型未定义.equalsIgnoreCase
,有什么方法可以在ArrayList
找到一个String
,而无需使用.equalsIgnoreCase
忽略大小写吗?
public static int findDog(String toFind, ArrayList<Dog> dogs)
{
for (int i = 0 ; i < dogs.size() ; i++)
{
if (dogs.get(i).equalsIgnoreCase(toFind))
{
return i;
}
}
return -1;
}
Dog
具有如下公共构造函数:
public Dog(String name, double age, double weight)
您不能将Dog
与String
进行比较,假设Dog
具有某些String
属性,则可以使用以下方法进行比较:
例:
if (dogs.get(i).getName().equalsIgnoreCase(toFind)){
return i;
}
在if循环的get(i)之后添加.getName()
像:if(dogs.get(i).. getName()。equalsIgnoreCase(toFind))
请参阅, .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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.