簡體   English   中英

對象ArrayList屬性

[英]Object ArrayList attributes

例如我有一個對象的arraylist。 具有這些屬性的學生對象

public Student(String name, String address)
{
  if (name == null)
     name = "";
  if (address == null)
     address = "";
  this.name = name;
  this.address = address;
  lastAssignedNumber++;//Starts at 1000
  studentNum = lastAssignedNumber;
  // at first no credits have been taken (so no grade points either)
  totalCredits = 0;
  totalPoints = 0.0;

}

假設我已將多個對象添加到此arraylist中。 我想根據studentNum編輯數組列表中的一個對象。

讓我們將arraylist稱為mylist:

我知道mylist.get(studentNum)不起作用,因為它獲取列表的索引。 有沒有一種方法可以基於studentNum編輯某個對象?

滿足您需求的最佳選擇是將Map接口與任何具體實現一起使用。

然后,鍵值對將以IdLong ,將Student對象作為value

Map<Long,Student> students= new HashMap<Long,Student>();

然后您可以將其用作

students.put(stu.getId(), student);

得到

  Student st=  students.get(stu.getId());

否則,每次都會導致迭代

假設我正在尋找一個學生人數為32的學生

for(Student s : mylist) {
  if(32 == s.getStudentNum) {
    theStudent = s;
  }
}

這是假設上面的數據結構,如果您想創建一個以studentNum為鍵,以student對象為值的地圖,那將是更合適的。

您可以使用地圖:

Map<Integer, Student> students = new HashMap<>();

放置學生和身份證:

students.put(studentNum, student);

並通過ID獲取學生:

students.get(studentNum);

如果您的Student對象在考慮studentNumber字段的情況下覆蓋了 equals ,則可以通過示例查找來獲取Student

首先創建一個例子

Student example = new Student();
s.setStudentNum(32); //If you want to find student with id 32

那么你可以通過示例找到

Student toFind = arrayList.get(arrayList.indexOf(example));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM