ArrayList模拟数据库的增删改查

模拟数据库的增删改查

import java.util.ArrayList;
import java.util.List;

public class homework {
    public static void main(String[] args) {
        UserService userServicer =new UserService();
        System.out.println("-------------------添加--------------");
        userServicer.add(new User("马忠义",25,"男"));
        userServicer.add(new User("潘佩珠",25,"女"));
        userServicer.add(new User("罗芷萍",21,"女"));
        userServicer.add(new User("刘新芳",23,"女"));
        System.out.println("-------------------输出结果---------");
        userServicer.print();
        System.out.println("-------------------修改---------");
        userServicer.update(new User("罗芷萍", 18, "拜拜"));
        userServicer.print();
        System.out.println("-------------------删除---------");
        userServicer.delete("刘新芳");
        userServicer.print();
    }

}
class User{
    private String name;
    private int age;
    private String sex;

    public User(String name, int age, String sex) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    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 String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }

}

用户管理类,提供对用户的增删改查(CRUD增删改查的第一个字母)

class UserService{
    private Listuser;
    public UserService(){
        user=new ArrayList();
    }
    /**
     * 增加方法
     * @param usr
     */
    public void add(User usr){
        user.add(usr);

    }
    /**
     * 
     * @param usr
     */
    public void update(User user){

        User u=find(user.getName());
        if (u==null){

            return;
        }
        else {
            //修改属性
            u.setAge(user.getAge());
            u.setSex(user.getSex());
        }
    }
    /**
     * 根据名字删除
     * @param name
     */
    public void delete(String name){
        User u=find(name);
        if (u==null){
            return;
        }
        user.remove(u);
    }
    /**
     查找方法,根据名字查
     * @param name
     */
    public User find(String name){  

        for(int i=0;iif (u.getName().equals(name)){
                return u;       
        }
            }

        return null;

    }
    /**
     * 输出所有用户
     */
    public void print(){
        for(int i=0;i

你可能感兴趣的:(java学习)