Java实现增删查改的基本步骤
1、定义数据结构
2、实现增加操作
3、实现删除操作
4、实现查询操作
5、实现更新操作
具体实现
1、定义数据结构
public class Student { private int id; private String name; private int age; public Student(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } // getter和setter方法省略 }
2、实现增加操作
import java.util.ArrayList; import java.util.List; public class StudentManager { private List<Student> students = new ArrayList<>(); public void addStudent(Student student) { students.add(student); } }
3、实现删除操作
public void deleteStudent(int id) { for (Student student : students) { if (student.getId() == id) { students.remove(student); break; } } }
4、实现查询操作
public Student findStudentById(int id) { for (Student student : students) { if (student.getId() == id) { return student; } } return null; }
5、实现更新操作
public void updateStudent(Student updatedStudent) { for (Student student : students) { if (student.getId() == updatedStudent.getId()) { student.setName(updatedStudent.getName()); student.setAge(updatedStudent.getAge()); break; } } }
完整示例代码
import java.util.ArrayList; import java.util.List; public class StudentManager { private List<Student> students = new ArrayList<>(); public void addStudent(Student student) { students.add(student); } public void deleteStudent(int id) { for (Student student : students) { if (student.getId() == id) { students.remove(student); break; } } } public Student findStudentById(int id) { for (Student student : students) { if (student.getId() == id) { return student; } } return null; } public void updateStudent(Student updatedStudent) { for (Student student : students) { if (student.getId() == updatedStudent.getId()) { student.setName(updatedStudent.getName()); student.setAge(updatedStudent.getAge()); break; } } } }
最新评论
本站CDN与莫名CDN同款、亚太CDN、速度还不错,值得推荐。
感谢推荐我们公司产品、有什么活动会第一时间公布!
我在用这类站群服务器、还可以. 用很多年了。