//对象数组与管理
public class LL {
public static void main(String[] args) {
ChickenManager c = new ChickenManager(2);
System.out.println("---------测试添加功能----------");
c.add(new Chicken(1, "艾克", 1));
c.add(new Chicken(2, "时间刺客", 2));
c.printlnALL();
System.out.println("---------测试添加数据数量超过数组长度时:----------");
c.add(new Chicken(3, "诺手", 3));
c.printlnALL();
System.out.println("---------测试删除功能:----------");
c.delete(3);
c.printlnALL();
System.out.println("---------测试更改功能:----------");
c.update(new Chicken(1, "菜", 11));
c.printlnALL();
System.out.println("---------测试单个查询功能:----------");
Chicken cc = c.find(1);
cc.printALl();
}
}
// 小鸡管理类
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[3];
}
}
// 增加小鸡
public void add(Chicken c) {
if (count >= cs.length) {
int temp = cs.length * 3 / 2 + 1;// 将数组扩充为原来的一半
cs = Arrays.copyOf(cs, temp);
}
cs[count++] = c;
}
// 删除小鸡
public void delete(int id) {
for (int i = 0; i < count; i++) {
if (cs[i].getId() == id) {
for (int j = i; j < count - 1; j++) {
cs[j] = cs[j + 1];
}
}
}
cs[count - 1] = null;
count--;
}
// 更新小鸡信息
public void update(Chicken c) {
Chicken temp = find(c.getId());
if (temp != null) {
temp.setAge(c.getAge());
temp.setName(c.getName());
}
}
// 查找小鸡
public Chicken find(int id) {
for (int i = 0; i < count; i++) {
if (cs[i].getId() == id) {
return cs[i];
}
}
return null;
}
// 打印全部的小鸡
public void printlnALL() {
for (int i = 0; i < count; i++) {
cs[i].printALl();
}
}
}
// 小鸡类
class Chicken {
private int id;
private String name;
private int age;
Chicken() {
}// 保留默认的构造方法
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 printALl() {
System.out.println("小鸡的ID:" + id + ",name:" + name + ",age:" + age + ".");
}
}