溫馨提示×

Java怎么往數(shù)組里添加對象

小億
196
2023-11-13 18:00:54
欄目: 編程語言

在Java中,可以使用以下方法將對象添加到數(shù)組中:

  1. 使用普通數(shù)組:如果數(shù)組是普通數(shù)組(即固定長度的數(shù)組),可以先創(chuàng)建一個新的數(shù)組,然后將原數(shù)組中的元素復制到新數(shù)組中,并將新對象添加到新數(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;
  1. 使用ArrayList:如果數(shù)組是ArrayList(即可變長度的數(shù)組),可以直接使用ArrayList的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ù)組中。

0