ArrayList
在循环中声明对象时如何知道对象的名称?我可以通过索引来获取它,但我不知道它的名称来定位/知道它是否在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;
}
}