集合练习
需求: 1.main方法中定义过一个集合,存入三个用户对象 用户属性为:id,name,password 2.要求:定义一个方法,根据id查找对应的用户信息 如果存在,返回true 如果不存在,返回false
对象类:
public class User {
private String id;
private String name;
private String password;
public User() {
}
public User(String id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
测试类:
import java.util.ArrayList;
public class TestUser {
public static void main(String[] args) {
// 创建集合
ArrayList<User> kon = new ArrayList<>();
User s1 = new User("id001", "张三", "123456");
User s2 = new User("id002", "李四", "234567");
User s3 = new User("id003", "王五", "345678");
kon.add(s1);
kon.add(s2);
kon.add(s3);
System.out.println(contains(kon, "id001"));
}
public static boolean contains(ArrayList<User> kon, String id) {
for (int i = 0; i < kon.size(); i++) {
User stu = kon.get(i);
String str = stu.getId();
if (str.equals(id)) {
return true;
}
}
return false;
}
}