将新元素添加到数组时,java.lang.ArrayIndexOutOfBoundsException? [英] java.lang.ArrayIndexOutOfBoundsException when adding new elements to an array?

查看:475
本文介绍了将新元素添加到数组时,java.lang.ArrayIndexOutOfBoundsException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Java 类,它将Person对象添加到现有Person Array

I have the following Java class that adds a Person object to an existing Person Array:

 public class PersonService{

 protected int lastItemInPersonArray = 0;

 private Person[] persons = new Person[100];


 public void addPersonToPersonArray(Person personToAdd){

        persons[lastItemInPersonArray++] = personToAdd;

    }

}

我可以添加1对象在这里正确,但当我尝试2我得到以下错误:

I can add 1 object correctly here but when I try to 2 I get the following error:

java.lang.ArrayIndexOutOfBoundsException: 1

导致这种情况的逻辑错误是什么?

What is incorrect with my logic that is causing this?

推荐答案

这对我有用。

public class PersonService {
    protected int lastItemInPersonArray = 0;
    private Person[] persons = new Person[100];
    public void addPersonToPersonArray(Person personToAdd) {
        persons[lastItemInPersonArray++] = personToAdd;
    }   
    public static void main(String[] args) {
        PersonService ps = new PersonService();
        ps.addPersonToPersonArray(new Person("P 1"));
        ps.addPersonToPersonArray(new Person("P 2"));
        ps.addPersonToPersonArray(new Person("P 3"));   
        System.out.println(ps.persons[0].nome);
        System.out.println(ps.persons[1].nome);
        System.out.println(ps.persons[2].nome);
    }
}
class Person{
    public Person(String nome) {
        this.nome = nome;
    }
    String nome;
}

这篇关于将新元素添加到数组时,java.lang.ArrayIndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆