Tom Perry
Tom Perry

Reputation: 9

How do I fix this ArrayIndexOutOfBoundsException?

for my program (I'm trying to run a private server source code for a game server), when I try to run the file as a Java Application it gives me the following error:

[Launcher] Initing Cache...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at com.rs.utils.huffman.Huffman.init(Huffman.java:15)
    at com.rs.Launcher.main(Launcher.java:65)

Now, I'm not sure if I'm supposed to change something within the Cache? But here is the line that it is giving the error:

byte[] huffmanFile = Cache.STORE.getIndexes()[10].getFile(Cache.STORE
        .getIndexes()[10].getArchiveId("huffman"));

Upvotes: -1

Views: 286

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

The direct check is Cache.STORE.getIndexes().length > 10. This is small code to clarify it:

1 Method to get required index from array with array length checking:

private static Cache.Index getIndex(Cache cache, int id) {
    Cache.Index[] indices = cache.getIndexes();
    return indices.length > id ? indices[id] : null;
}

2 This is required index as named constant:

private static final int ID_HUFFMAN = 10;

3 This is the code from you answer but not in one line (to make it absolute clear):

Cache.Index huffman = getIndex(Cache.STORE, ID_HUFFMAN);

if (huffman != null) {
    String archiveId = huffman.getArchiveId("huffman");
    byte[] huffmanFile = huffman.getFile(archiveId);
}

P.S. This is how I represent model of your Cache class:

class Cache {
    static final Cache STORE = new Cache();

    class Index {
        public byte[] getFile(String archiveId) {}
        public String getArchiveId(String id) {}
    }

    public Index[] getIndexes() {}
}

Upvotes: 0

yassadi
yassadi

Reputation: 524

Check the size of your array by the following manner:

Cache.STORE.getIndexes().length > 10

So your code will look like:

if(Cache.STORE.getIndexes().length > 10)
   byte[] huffmanFile = Cache.STORE.getIndexes()[10].getFile(Cache.STORE
        .getIndexes()[10].getArchiveId("huffman"));

Upvotes: 1

Mesar ali
Mesar ali

Reputation: 1898

you can check size before trying to access it

if(Cache.STORE.getIndexes().length > 10){
byte[] huffmanFile = Cache.STORE.getIndexes()[10].getFile(Cache.STORE
    .getIndexes()[10].getArchiveId("huffman"));
}

Upvotes: 1

Related Questions