【问题标题】:how to compare arraylist with String whilst ignoring capitalization?如何在忽略大写的情况下将arraylist与String进行比较?
【发布时间】:2018-04-12 21:15:54
【问题描述】:

我收到一条错误消息,指出 .equalsIgnoreCase 对于 Dog 类型未定义,有什么方法可以在 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)

【问题讨论】:

  • 你应该如何比较DogString?是否有一些字符串变量 in Dog 您要比较?
  • 也许您希望 dogs.get(i).getName()dogs.get(i).toString() 与字符串进行比较,我猜它代表名称或其他属性?
  • Dog是public Dog(String name, double age, double weight)的构造函数

标签: java string arraylist ignore-case


【解决方案1】:

您无法将DogString 进行比较,假设Dog 具有一些String 属性,那么您可以这样做:

示例:

if (dogs.get(i).getName().equalsIgnoreCase(toFind)){
       return i;
}

【讨论】:

  • 谢谢。是的 Dog 有一个 String 属性,很抱歉没有在问题中指定它!
  • @meli 没关系,刚刚更新了您的描述。你不必抱歉:)
【解决方案2】:

看,.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 中的代码即可。 Read More

好的。现在你的代码将是:

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;           
      }

【讨论】:

    【解决方案3】:

    在 if 循环中的 get(i) 之后添加 .getName()

    喜欢:if (dogs.get(i)..getName().equalsIgnoreCase(toFind))

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2020-09-28
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多