生成一段实现对用户信息增删改查的java代码
时间: 2023-11-18 10:04:17 浏览: 90
好的,以下是一个简单的用户信息增删改查的Java代码示例:
```
import java.util.ArrayList;
import java.util.List;
public class User {
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// getter and setter methods
public int getId() {
return id;
}
public void setId(int 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 class UserRepository {
private List<User> users;
public UserRepository() {
users = new ArrayList<User>();
}
public void addUser(User user) {
users.add(user);
}
public void updateUser(User user) {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getId() == user.getId()) {
users.set(i, user);
break;
}
}
}
public void deleteUser(int id) {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getId() == id) {
users.remove(i);
break;
}
}
}
public User getUserById(int id) {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getId() == id) {
return users.get(i);
}
}
return null;
}
public List<User> getAllUsers() {
return users;
}
}
// Usage example
public class Main {
public static void main(String[] args) {
UserRepository userRepository = new UserRepository();
// add new user
User user1 = new User(1, "John", 25);
userRepository.addUser(user1);
// update user
User user2 = new User(1, "John Doe", 30);
userRepository.updateUser(user2);
// delete user
userRepository.deleteUser(1);
// get user by ID
User user3 = userRepository.getUserById(2);
// get all users
List<User> allUsers = userRepository.getAllUsers();
}
}
```
这段代码包含了一个用户类和一个用户仓库类,可以实现用户信息的增删改查功能。用户类包含了用户的基本信息,用户仓库类包含了增加、更新、删除、查询用户信息的方法。在主函数中,可以实例化一个用户仓库对象,并使用它来实现用户信息的增删改查。
阅读全文