How to know if there is an element in a List index without error?

Asked

Viewed 508 times

3

I’m trying to give a get() in the indices of a ArrayList, so that if there is something in those positions, I add that value with something else. Only if there is no such index, I would add it.

However, the IDE already gives "Index out of Bounds" as soon as I give a get an index that does not exist. It could not simply return null? Or something like that?

The line of error is:

aColorCount = byColorCount.get(ar[x]);

The code snippet:

 static int sockMerchant(int n, int[] ar) {
        List<Integer> byColorCount = new ArrayList(100);
        int aColorCount = -1;
        for(int x=0; x<ar.length; x++){
//Eu ia fazer um if abaixo, pra ver se o elemento existe, mas só da dar get já estoura a lista
           aColorCount = byColorCount.get(ar[x]);

           byColorCount.add(ar[x], aColorCount++);
        }

1 answer

5


The builder new ArrayList(100) is only setting the initial capacity to 100, but the list itself will have no element. Just note that the code below prints 0:

System.out.println(new ArrayList(100).size()); // 0

That is, the created list is empty: any access to any index with get - inclusive get(0) - will give error, since the list has no element.

That one 100 is only the initial capacity. Basically, when the list is created, a certain amount of items is pre-allocated internally (in this case, 100). It means that this list has 100 spaces available to store elements. As you add elements to the list, these spaces are being used. When it is checked that there is no more space, the list allocates more capacity automatically (read the documentation for more details).

In your case it is not very clear what you want. You are creating a list with nothing and want to check if there is something in it (but never will be, because it is empty).

If you want to start the list with 100 elements, you can use Collections.nCopies:

List<Integer> byColorCount = new ArrayList<Integer>(Collections.nCopies(100, null));

So the list will have 100 elements, and all of them will be null. Or you can use Collections.nCopies(100, 0) so that everyone is zero, for example (or do the good old for to add 100 elements).

Then just check if ar[x] is not greater than the amount of array elements, and if the value is null:

List<Integer> byColorCount = new ArrayList<Integer>(Collections.nCopies(100, null));

for (int x = 0; x < ar.length; x++) {
    if (ar[x] >= 0 && ar[x] < byColorCount.size()) {
        // verifica se byColorCount.get(ar[x]) não é null
        if (byColorCount.get(ar[x]) != null) {
            // faz o que quiser com byColorCount.get(ar[x])
        } else {
            // elemento é nulo, setar para outro valor
            byColorCount.set(ar[x], x);
        }
    }
}

It’s unclear why you’re wearing ar[x] as the index, and as this array can have any value, it is better to check first whether this value is not greater than the amount of elements in the list - and also if it is not negative (the first if). So you avoid the IndexOutOfboundsException.

Then just check whether the element is null or not and take the actions according to each case.

  • Your first example solves what I need. But what I still don’t understand is this: if I use a Linkedlist for example, can I insert elements in sparse indexes? And I want to check if a certain sparse index exists in the list. Is there a way? Maybe Try catch works, what do you think?

  • 1

    @Lucaspletsch LinkedList is a list too, and if you create one with x elements and try to access x + 1, it will give error. If you want sparse elements, maybe the best way is to emulate it with a Map.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.