共計 753 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用循環來遍歷實體類的屬性值。假設有一個名為 Person 的實體類,包含屬性 name 和 age,以下是兩種常用的循環實體類取值的方法:
- 使用 for-each 循環:
List<Person> personList = new ArrayList<>(); // 假設有一個 Person 對象列表
for (Person person : personList) {System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
在上述代碼中,通過 for-each 循環遍歷 personList 列表中的每個 Person 對象。通過調用每個 Person 對象的 getName() 和 getAge() 方法,可以獲取并打印每個對象的 name 和 age 屬性值。
- 使用普通 for 循環:
List<Person> personList = new ArrayList<>(); // 假設有一個 Person 對象列表
for (int i = 0; i < personList.size(); i++) {Person person = personList.get(i);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
在上述代碼中,使用普通的 for 循環遍歷 personList 列表。通過調用 personList.get(i) 方法獲取每個索引位置上的 Person 對象,并通過 getName() 和 getAge() 方法獲取屬性值。
無論使用哪種方法,循環實體類取值的核心是遍歷實體類對象,并使用對象的方法獲取屬性值。
丸趣 TV 網 – 提供最優質的資源集合!
正文完