java JAVA迭代器ITERATOR增删改查

葫芦的运维日志

下一篇 搜索 上一篇

浏览量 4546

2015/01/24 01:43


import java.util.*;
class User {
        private String name ;
        private int age ;
        @Override
        public String toString() {
               return "User [name=" + name + ", age=" + age + "]" ;
       }
        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 User(String name, int age) {
               super();
               this.name = name;
               this.age = age;
       }
        public User() {
               super();
               // TODO 自动生成的构造函数存根
       }
}
class UserService
{
        private List<User> users ;
        public UserService(){
               users= new ArrayList<User>();
       }
public User find(String name){
Iterator<User> it=users.iterator();
while(it.hasNext()){
User u=it.next();
if (u.getName().equals(name))
{return u;
}
}
return null;
}

public void update(User user){
User u=find(user.getName());
if (u==null ){return;
}
u.setAge(user.getAge());
}
public void del(String name){
Iterator<User> it=users.iterator();
while(it.hasNext()){
User u=it.next();
if (u.getName().equals(name))
{it.remove();
}
}}
public void add(User user){
users.add(user);
}
public void print(){
Iterator it=users.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
public class Test
{
        public static void main(String[] args){

       UserService us= new UserService();
System.out.println("增加");
       us.add( new User("wangzi" ,20));
    us.add(new User( "wangzimu",220));
              us.print();
System.out.println( "查找");

       User u=us.find( "wangzi");

       System. out.println(u);
       System. out.println("修改" );
us.update(new User( "wangzi",10));
                     us.print();
System.out.println( "删除");
              us.del( "wangzimu");
       us.print();


       }
}

增加
User [name=wangzi, age=20]
User [name=wangzimu, age=220]
查找
User [name=wangzi, age=20]
修改
User [name=wangzi, age=10]
User [name=wangzimu, age=220]
删除
User [name=wangzi, age=10]
请按任意键继续. . .

 

葫芦的运维日志

打赏

上一篇 搜索 下一篇
© 冰糖葫芦甜(bthlt.com) 2021 王梓打赏联系方式 陕ICP备17005322号-1