本文介绍了如何避免java.lang.ArrayIndexOutOfBoundsException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你的问题是的我在我的code得到一个 java.lang.ArrayIndexOutOfBoundsException ,我不明白为什么它正在发生。这是什么意思,我怎样能避免呢?


解决方案

What is java.lang.ArrayIndexOutOfBoundsException?

The JavaDoc curtly states:

What causes it to happen?

final String days[] { "Sunday", "Monday", "Tuesday" }
System.out.println(days.length); // 3
System.out.println(days[0]); // Sunday
System.out.println(days[1]); // Monday
System.out.println(days[2]); // Tuesday
System.out.println(days[3]); // java.lang.ArrayIndexOutOfBoundsException

This also applies to ArrayList as well as any other Collection classes that may be backed by an Array and allow direct access to the the index.

How to avoid the java.lang.ArrayIndexOutOfBoundsException?

When accessing directly by index:

final List<Integer> toTen = ImmutableList.copyOf(Ints.asList(ints));
System.out.println(Iterables.get(toTen, 0, -1));
System.out.println(Iterables.get(toTen, 100, -1));

If you can't use Guava for some reason it is easy to roll your own function to do this same thing.

private static <T> T get(@Nonnull final Iterable<T> iterable, final int index, @Nonnull final T missing)
{
    if (index < 0) { return missing; }
    if (iterable instanceof List)
    {
        final List<T> l = List.class.cast(iterable);
        return l.size() <= index ? l.get(index) : missing;
    }
    else
    {
        final Iterator<T> iterator = iterable.iterator();
        for (int i = 0; iterator.hasNext(); i++)
        {
            final T o = iterator.next();
            if (i == index) { return o; }
        }
        return missing;
    }
}

When iterating:

Using a traditional for/next loop:

final int ints[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < ints.length; i++)
{
    System.out.format("index %d = %d", i, ints[i]);
}

Using an enhanced for/each loop:

for (final int i : ints)
{
    System.out.format("%d", i);
    System.out.println();
}

Using a type safe Iterator:

final Iterator<Integer> it = Ints.asList(ints).iterator();
for (int i = 0; it.hasNext(); i++)
{
    System.out.format("index %d = %d", i, it.next());
}

If you can not use Guava or your int[] is huge you can roll your own ImmutableIntArrayIterator as such:

public class ImmutableIntArrayIterator implements Iterator<Integer>
{
    private final int[] ba;
    private int currentIndex;

    public ImmutableIntArrayIterator(@Nonnull final int[] ba)
    {
        this.ba = ba;
        if (this.ba.length > 0) { this.currentIndex = 0; }
        else { currentIndex = -1; }
    }

    @Override
    public boolean hasNext() { return this.currentIndex >= 0 && this.currentIndex + 1 < this.ba.length; }

    @Override
    public Integer next()
    {
        this.currentIndex++;
        return this.ba[this.currentIndex];
    }

    @Override
    public void remove() { throw new UnsupportedOperationException(); }
}

And use the same code as you would with Guava.

If you absolutely must have the ordinal of the item the following is the safest way to do it.

// assume los is a list of Strings
final Iterator<String> it = los.iterator();
for (int i = 0; it.hasNext(); i++)
{
    System.out.format("index %d = %s", i, it.next());
}

This technique works for all Iterables, it is not an index perse but it does give you the current position in the iteration even for things that do not have a native index.

The safest way:

final List<Integer> ili = ImmutableList.copyOf(Ints.asList(ints));
final Iterator<Integer> iit = ili.iterator();
for (int i = 0; iit.hasNext(); i++)
{
    System.out.format("index %d = %d", i, iit.next());
}

Summary:

  1. Using raw Array are difficult to work with and should be avoided in most cases. They are susceptible to sometimes subtle one off errors which have plague new programmers even back to the days of BASIC
  2. Modern Java idioms use proper type safe Collections and avoid using raw Array structures if at all possible.
  3. Immutable types are preferred in almost all cases now.
  4. Guava is an indispensable toolkit for modern Java development.

这篇关于如何避免java.lang.ArrayIndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:27