1、实现功能:
- 基于数组实现,数组长度由用户输入,数组会进行动态扩充
- 扩充原理:扩充长度为原数组长度的2倍
- 可进行添加、修改、删除、查询操作。
2、代码实现
2.1、Chicken.java
public 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; } // get,set }
2.2、ChickenManager.java
public class ChickenManager { private static int count = 0;//用来判断数组中有几个对象 private Chicken[] chickens; // 数组对象 // 如果用户输入小于0,则默认数组长度为5 public ChickenManager(int size) { if (size > 0) { chickens = new Chicken[size]; } else { chickens = new Chicken[5]; } } /** * 获取数组的长度 */ public int getLength() { return chickens.length; } // 添加方法 public void add(Chicken... chicken) { for (Chicken c : chicken ) { if (count >= chickens.length) { // 需要扩充数组(扩充一半 *3/2+1,扩充一倍*2) // chickens = Arrays.copyOf(chickens,chickens.length*2); Chicken[] chickens1 = new Chicken[chickens.length * 2]; System.arraycopy(chickens, 0, chickens1, 0, chickens.length); chickens = chickens1; } chickens[count] = c; count++; } } // 删除方法 public void delete(int id) { for (int i = 0; i < count; i++) { if (chickens[i].getId() == id) { // 删除后,后面所有元素需要向前移动 if (count - 1 - i >= 0) { System.arraycopy(chickens, i + 1, chickens, i, count - 1 - i); } chickens[count - 1] = null; count--; break; } } } // 修改 public void update(Chicken chicken) { Chicken chicken1 = selectById(chicken.getId()); if (chicken1 != null) { chicken1.setAge(chicken.getAge()); chicken1.setName(chicken.getName()); } } // 查询 public void select() { System.out.println(Arrays.toString(chickens)); } // 根据id查询 public Chicken selectById(int id) { for (int i = 0; i < count; i++) { if (chickens[i].getId() == id) { return chickens[i]; } } return null; } }
3、测试
public class Test8 { public static void main(String[] args) { // 默认数组长度为1 ChickenManager chickenManager = new ChickenManager(1); // 添加,数组会动态扩充 chickenManager.add(new Chicken(1, "花花", 12), new Chicken(2, "詹三", 23), new Chicken(3, "嘿嘿", 12), new Chicken(4, "丽丽", 32), new Chicken(5, "杨洋", 23)); // 增删改查操作 } }