Add Strings in-between index of ArrayList if not already exists So as the title states, I am trying to add a specific Items to an ArrayList if they not already exist. So here is how the Array starts.

[a, b, c, d, e, f]


I have this items inside the ArrayList

and I'm gonna add some items after the item d if it doesn't exist already in a pattern.

[a, b, c, d, x, y, z, e, f]


I had a successful run of the items I have provided resulting with the output

[a, b, c, d, e, f]
Adding string x to index 3
Adding string y to index 4
Adding string z to index 5
[a, b, c, d, x, y, z, e, f]
String already exists x skipping...
String already exists y skipping...
String already exists z skipping...
[a, b, c, d, x, y, z, e, f]


here is the code that I have created to get this result

public static void addStringIfNotAlreadyExists(List&lt;String&gt; list, int index, String... strings) {
    for (String s : strings) {
        if (!list.get(index + 1).equals(s)) {
            System.out.println("Adding string " + s + " to index " + index);
            list.add(index + 1, s);
        } else {
            System.out.println("String already exists " + s + " skipping...");
        }
        index++;
    }
}


It's not the best code I have written but it works.

and here is how I call it for the test.

public static void main(String[] args) {
    List&lt;String&gt; list = new ArrayList&lt;&gt;();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("e");
    list.add("f");
    System.out.println(list);
    addStringIfNotAlreadyExists(list, 3, "x", "y", "z");
    System.out.println(list);
    addStringIfNotAlreadyExists(list, 3, "x", "y", "z");
    System.out.println(list);
}


What I am curious in if this code can fail in certain tests, Or how I can improve the code.
A few things come to mind:


First of all, as you access the list at index + 1 without any bounds check, the code will fail if a user attempts to use the method to add elements to the end of the string. You should probably handle that gracefully.
Changing the input parameter's value index is not expressedly forbidden, but it makes my skin crawl. Furthermore, you have to coordinate two values in a loop (s and index) which makes the code error prone. In this case, I'd go for an index based loop instead for(int i = 0; i &lt; strings.length; i++) and use strings[i] and list.get(index + i). This way, you have only a single variable changing in the loop.
If there's nulls in the list, the code will throw an NPE. Preferably use Objects.equals(x, y) instead of x.equals(y) to stay null-safe.