John White
John White

Reputation: 21

Comparing a String Array to Array List

I currently have a String Array

String[] properSequence = ability.getSequence();

And I want to compare it to an ArrayList

ArrayList<String> sequence

As of right now I'm doing,

boolean matchesSequence = true;

String[] properSequence = ability.getSequence();

int index = 0;
for(String s : sequence) {
   String s1 = properSequence[index];
   if(!s1.equalsIgnoreCase(s)) {
      matchesSequence = false;
      break;
   }
   index++;
}

if(matchesSequence) {
   // Matches, code
}

I was wondering if there's an easier/prettier way of doing this, seems a bit redundant.

Upvotes: 2

Views: 1004

Answers (4)

WJS
WJS

Reputation: 40024

Arrays and Lists are only considered equal to each other if the elements are equal and in the same order.

To compare an Array of object to a List of the same object you can do the following using the Arrays#compare method. Different versions have different capabilities. This example uses Strings and does a case insensitive compare. It also makes use of List.toArray introduced in JDK 11

List<String> list = List.of("A", "B", "C");
String[] array1 = { "a", "b", "c" };
String[] array2 = { "a", "c", "b" };

for (String[] array : new String[][] { array1, array2 }) {
    
    if (Arrays.compare(array, list.toArray(String[]::new),
            String.CASE_INSENSITIVE_ORDER) == 0) {
        System.out.printf("%s equals %s%n",
                Arrays.toString(array), list);
    } else {
        System.out.printf("%s does not equal %s%n",
                Arrays.toString(array), list);
    }
}

Prints

[a, b, c] equals [A, B, C]
[a, c, b] does not equal [A, B, C]

Upvotes: 1

Jonathan Locke
Jonathan Locke

Reputation: 303

You could convert the String[] into an ArrayList and compare those two, but you can't do that if you want equalsIgnoreCase() in the comparison. However, if you put all the elements in the String[] and the ArrayList in upper (or lower) case, you could do this:

if (Arrays.asList(properSequence).equals(sequence)) 
{
   ...
}

Upvotes: 1

Deepak
Deepak

Reputation: 123

You can use built-in equals method:

if(!Arrays.equals(sequence.toArray(),properSequence))
    matchesSequence = false;

Upvotes: 1

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 78965

Your code may throw ArrayIndexOutOfBoundsException. Check the bounds of array as well as the list as shown below:

for(int i = 0; i < Math.min(sequence.size(), properSequence.length); i++) {
   if(!sequence.get(i).equalsIgnoreCase(properSequence[i])) {
      matchesSequence = false;
      break;
   }
}

Alternatively,

for(int i = 0; i < sequence.size() && i < properSequence.length; i++) {
   if(!sequence.get(i).equalsIgnoreCase(properSequence[i])) {
      matchesSequence = false;
      break;
   }
}

Upvotes: 1

Related Questions