//学生类
package cn.itsource_01review;
public class Studaent {
private Integer id;
private String name;
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Studaent(Integer id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Studaent [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
//学生的增删改查
package cn.itsource_01review;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StudentDoa {
private static List<Studaent> stu = new ArrayList();
//查询所有
public List<Studaent>query(){
return stu;
}
//id 查询一个
public Studaent queryOne(Integer id){
//获得一个迭代器
Iterator<Studaent> iterator = stu.iterator();
while (iterator.hasNext()) {
Studaent next = iterator.next();
if (next.getId().equals(id)) {
return next;
}
}
return null;
}
//添加
public void add(Studaent s){
if (stu.size()<=0) {
stu.add(s);
} else {
for (int i = 0; i < stu.size(); i++) {
Studaent studaent = stu.get(i);
if (studaent.getId().equals(s.getId())) {
return;
}
}
stu.add(s);
}
}
//删除
public boolean dele(int id){
//调用查询方法
Studaent student = queryOne(id);
return stu.remove(student);
}
//修改
public void update(Studaent s){
Studaent Student = queryOne(s.getId());
int indexOf = stu.indexOf(Student);
if (indexOf>=0) {
stu.set(indexOf, s);
}
}
}
//测试类
package cn.itsource_01review;
import java.util.List;
public class Test {
public static void main(String[] args) {
StudentDoa ddd = new StudentDoa();
ddd.add(new Studaent(1, "小A", 12));
ddd.add(new Studaent(2, "小B", 12));
ddd.add(new Studaent(3, "小C", 12));
ddd.add(new Studaent(5, "小D", 12));
ddd.add(new Studaent(6, "小F", 12));
ddd.add(new Studaent(6, "小E", 12));
ddd.add(new Studaent(7, "小G", 12));
ddd.add(new Studaent(9, "小K", 12));
ddd.update(new Studaent(1, "小B", 12));
System.out.println(ddd.dele(2));
List<Studaent> query = ddd.query();
System.out.println(query);
}
}