[英]how to compare arraylist with String whilst ignoring capitalization?
I am getting an error saying that .equalsIgnoreCase
is undefined for the type Dog
, is there any way to find a String
in the ArrayList
while ignoring capitalization without using .equalsIgnoreCase
? 我收到一个错误消息,说对于
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
has a public constructor like this: Dog
具有如下公共构造函数:
public Dog(String name, double age, double weight)
You cannot compare a Dog
with a String
, assuming Dog
has some String
property then you can do it with this: 您不能将
Dog
与String
进行比较,假设Dog
具有某些String
属性,则可以使用以下方法进行比较:
Example: 例:
if (dogs.get(i).getName().equalsIgnoreCase(toFind)){
return i;
}
add .getName() after get(i) in if loop 在if循环的get(i)之后添加.getName()
Like: if (dogs.get(i)..getName().equalsIgnoreCase(toFind)) 像:if(dogs.get(i).. getName()。equalsIgnoreCase(toFind))
See, .equalsIgnoreCase logic
will work with Dog absolutely fine but not like you did it. 请参阅,
.equalsIgnoreCase logic
绝对可以与Dog一起使用,但是不像您那样做。 Here's what you need to do. 这是您需要做的。
Let's say you want to say 2 dogs are same if they have same Name
. 假设您要说
2 dogs are same if they have same Name
。
Then Modify your Dog class as shown below : 然后修改您的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());
}
}
Now, whenever , you want to compare 2 dogs , the above compareTo
if it gives 0
then 2 Dogs are same else not same. 现在,无论何时,您要比较2条狗,上面的
compareTo
如果给出0
则2条狗相同,否则不一样。 Note that I am assuming 2 Dogs are same if they have same Name. 请注意,如果它们的名称相同,我假设2条狗相同。
If that is not the equality criteria , no need to worry. 如果这不是平等标准,则无需担心。 All you need to change is code inside
compareTo
according to your logic. 您需要更改的只是根据您的逻辑在
compareTo
内的代码。 Read More 阅读更多
Okay. 好的。 Now you code will be :
现在您的代码将是:
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.