问题
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