简体   繁体   中英

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 ?

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:

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:

Example:

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

add .getName() after get(i) in if loop

Like: if (dogs.get(i)..getName().equalsIgnoreCase(toFind))

See, .equalsIgnoreCase logic will work with Dog absolutely fine but not like you did it. Here's what you need to do.

Let's say you want to say 2 dogs are same if they have same Name .

Then Modify your Dog class as shown below :

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. Note that I am assuming 2 Dogs are same if they have same Name.

If that is not the equality criteria , no need to worry. All you need to change is code inside compareTo according to your logic. 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;           
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM