在Java中,可以使用以下方法將對象添加到數(shù)組中:
// 創(chuàng)建一個包含3個元素的Person對象數(shù)組
Person[] persons = new Person[3];
// 創(chuàng)建一個新的Person對象
Person newPerson = new Person("John", 25);
// 創(chuàng)建一個新的數(shù)組,長度比原數(shù)組大1
Person[] newArray = new Person[persons.length + 1];
// 將原數(shù)組中的元素復制到新數(shù)組中
System.arraycopy(persons, 0, newArray, 0, persons.length);
// 將新對象添加到新數(shù)組的末尾
newArray[persons.length] = newPerson;
// 將新數(shù)組賦值給原數(shù)組
persons = newArray;
add()
方法將對象添加到數(shù)組的末尾。以下是一個示例代碼:// 創(chuàng)建一個ArrayList對象
ArrayList<Person> persons = new ArrayList<>();
// 創(chuàng)建一個新的Person對象
Person newPerson = new Person("John", 25);
// 將新對象添加到ArrayList的末尾
persons.add(newPerson);
無論使用哪種方法,都需要使用相應的語法創(chuàng)建新對象,并將其添加到數(shù)組中。