java.lang.ArrayIndexOutOfBoundsException when adding new elements to an array? [closed]

浪子不回头ぞ 提交于 2019-12-25 20:57:14

问题


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;

    }

}

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?


回答1:


This works for me.

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;
}


来源:https://stackoverflow.com/questions/44305231/java-lang-arrayindexoutofboundsexception-when-adding-new-elements-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!