java10 OOP 对象数组与管理 2022-02-06

//对象数组与管理
import java.util.Arrays;
public class Test1 {
    public static void main(String[] args) {
        ChickenManager cm=new ChickenManager(5);
        //添加
        cm.add(new Chicken(1,"小一",10));
        cm.add(new Chicken(2,"小二",6));
        cm.add(new Chicken(3,"小三",6));
        cm.add(new Chicken(4,"小四",4));
        cm.add(new Chicken(5,"小五",3));

        cm.add(new Chicken(6,"小六",3));
        System.out.println(cm.length());//因为有第6个所以造成了数组扩充
        //查找
        System.out.println("++++++++find+++++++");
        Chicken c=cm.find(5);
        c.print();
        //打印所有
        System.out.println("++++++++printAll+++++++");
        cm.printAll();
        //更新
        System.out.println("++++++++update+++++++");
        cm.update(new Chicken(1,"下蛋公鸡",20));
        cm.printAll();

    }
}
//小鸡类(数据对象 value object(VO))
class Chicken{
    private int id;
    private String name;
    private int age;
    public Chicken() {}
    public Chicken(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    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 void print(){
        System.out.println("id="+id+"name="+name+"age="+age);
    }
}
//小鸡管理类
class ChickenManager{
    private Chicken[] cs=null;//多个小鸡(对象数组)
    private int count=0;//记录当前数组的元素个数(下标)
    public ChickenManager(int size) {
        if (size>0){
            cs=new Chicken[size];
        }else{
            cs=new Chicken[5];//默认定义五只
        }
    }
    public int length(){
        return cs.length;
    }
    //添加:实现动态数组
    public void add(Chicken c){
        if (count>=cs.length){//数组已满,需要扩充
            //算法一:扩充原数组大小的一半 cs.length*3/2+1
            //算法二:扩充原数组一倍 cs.length*2
            int newLen=cs.length*2;
            cs=Arrays.copyOf(cs,newLen);//创建新数组
        }
        cs[count]=c;
        count++;

    }
    //删除
    public void delete(int id){
        for (int i = 0; i < count; i++) {
            if(cs[i].getId()==id){
                //找到了要删除的对象,把该对象之后的对象向前移动一位
                for (int j = i; j 

你可能感兴趣的:(java10 OOP 对象数组与管理 2022-02-06)