![](/img/trans.png)
[英]Adding and setting new object in ArrayList at specific index (JAVA)
[英]Creating an arraylist of nulls and then setting the index to an object
真的需要幫助,因為患者沒有准備好替換空值。 我們必須創建一個包含 50 個空值的數組列表,以便迭代器遍歷列表,如果找到空值,它將設置為患者。 問題是沒有患者被設置為空值。 我們也必須在最后返回床號。
protected int amountOfBeds = 50;
ArrayList<Patient> bedList = new ArrayList<Patient>(amountOfBeds);
public int admitPatient(Patient illPatient) {
int index = -1;
if(illPatient.getAge() > 0 && amountOfBeds > size()) {
//if it is null then set to patient
//if it not null then we assume its a patient so we skip
Iterator<Patient> itr = bedList.iterator();
try{
while(itr.hasNext()) {
int bedIndex = bedList.indexOf(itr.next());
if(bedList.get(bedIndex).equals(null)) {
bedList.set(bedIndex, illPatient);
index = bedIndex +1;
break;
}
}
}catch(NullPointerException e) {
e.getMessage();
}
}
return index;
}
創建 50 個空值列表的簡單方法是這樣的
List<Patient> list = Collections.nCopies(50, null);
查找空索引的快速方法是這樣的
int i = list.indexOf(null);
在 Java 中, ArrayList
基本上是一個數組,可以在執行期間更改其大小。 由於您似乎有固定數量的床,因此在這里使用數組可能會更好。
構造函數new ArrayList(50)
不會創建具有 50 個元素的 ArrayList。 它創建了一個空的 ArrayList,但給 Java 一個“提示,可能會在 ArrayList 中插入 50 個元素。如果你不給出這樣的提示,ArrayList 開始時空間很小,並且會定期變大,如果它得到太小太小,無法容納您想要插入的所有項目。這需要時間,所以如果您已經知道要插入多少項目(即使您只知道大約),此構造函數會使您的代碼更快。
但是,您必須考慮是否真的需要按照您想要的方式執行此操作。 這不是更容易嗎,只有一個空的 ArrayList,您可以隨意添加或刪除元素(沒有復雜的邏輯,用元素替換null
。然后您可以添加if (array.size() >= 50) // it is full, so some special case may be needed here
來確保數組中的元素永遠不會超過你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.