如何在循環中聲明ArrayList
時知道對象的名稱? 我可以通過索引得到它,但我不知道它的名稱是要找到/知道它是否在ArrayList
。帶有循環中對象的Java ArrayList
import java.util.ArrayList;
public class Teste {
public static void main(String[] args) {
ArrayList<UserClasss> userList = new ArrayList<UserClasss>();
for (int i = 0; i < 5; i++) {
UserClasss user = new UserClasss();
user.setName("name"+i);
user.setAge((int)(Math.random()*80));
userList.add(user);
}
for (UserClasss forUser:userList){
System.out.println(forUser.getName());
System.out.println(forUser.getAge());
}
//how can i know if contains it here?
//userList.contains(user);
//and how do i know the index of it?
//userList.indexOf(user);
}
}
class UserClasss {
private String name;
private int age;
public void setName(String s){
name = s;
}
public String getName(){
return name;
}
public void setAge(int i){
age = i;
}
public int getAge(){
return age;
}
}
重寫'hashCode()'和'equals()'總是好的,而不僅僅是一個 – Sujay