如何修复此ArrayIndexOutOfBoundsException?

时间:2018-05-19 04:42:35

标签: java

对于我的程序(我正在尝试为游戏服务器运行私有服务器源代码),当我尝试将该文件作为Java应用程序运行时,它给出了以下错误:

[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)

现在,我不确定我是否应该更改缓存中的内容?但这是它给出错误的那一行:

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

3 个答案:

答案 0 :(得分:1)

您可以在尝试访问之前检查尺寸

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

答案 1 :(得分:1)

通过以下方式检查阵列的大小:

Cache.STORE.getIndexes().length > 10

所以你的代码看起来像是:

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

答案 2 :(得分:0)

直接检查是import { Component, Injectable } from '@angular/core'; /*import { NavController } from 'ionic-angular';*/ import { IonicPage } from 'ionic-angular/navigation/ionic-page'; import { AngularFireDatabase, AngularFireList } from 'angularfire2/database'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Note } from '../../model/note/note.model'; @Injectable() @IonicPage() @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { itemsRef: AngularFireList<any>; items: Observable<Note[]>; constructor(db: AngularFireDatabase) { this.itemsRef = db.list('note-list'); this.items = this.itemsRef.snapshotChanges().pipe( map(changes => changes.map(c => ({ key: c.payload.key, ...c.payload.val() })) ) ); } } 。这是一个很小的代码来澄清它:

1 通过数组长度检查从数组中获取所需索引的方法:

Cache.STORE.getIndexes().length > 10

2 这是必需的索引,名为constant:

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

3 这是您回答的代码,但不是一行(为了使其绝对清晰):

private static final int ID_HUFFMAN = 10;

<强> P.S。 这就是我代表Cache.Index huffman = getIndex(Cache.STORE, ID_HUFFMAN); if (huffman != null) { String archiveId = huffman.getArchiveId("huffman"); byte[] huffmanFile = huffman.getFile(archiveId); } 类的模型的方式:

Cache