public class Person { private String firstName; private String lastName; private int age; public Person(String firstName, String lastName, int age) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]"; } }
public class ClassDataArray { private Person[] a; private int size; public ClassDataArray(int max){ a = new Person[max]; size = 0; } public Person find(String searchLastName){ int i; for(i=0;i<size;i++){ if(a[i]!= null && searchLastName.equals(a[i].getLastName())){ return a[i]; } } return null; } public void insert(Person person){ a[size] = person; size++; } public boolean delete(String searchLastName){ int j; for(j=0;j<size;j++) if(searchLastName.equals(a[j].getLastName())) break; if(j==size) return false; else{ for(int k=j;k<size;k++) a[k] = a[k+1]; size--; return true; } } public void display(){ for(int i=0;i<size;i++){ System.out.println(a[i]); } } }
客户端
public class Clinet { public static void main(String[] args) { ClassDataArray array = new ClassDataArray(100); Person zhangsan = new Person("zhang", "san", 21); Person lisi = new Person("li", "si", 22); Person wangwu = new Person("wang", "wu", 13); Person lily = new Person("li", "ly", 56); Person rex = new Person("rex", "", 21); Person json = new Person("ja", "son", 23); Person mike = new Person("mi", "kel", 66); Person cloud = new Person("clou", "der", 19); array.insert(zhangsan); array.insert(lisi); array.insert(wangwu); array.insert(lily); array.insert(rex); array.insert(json); array.insert(mike); array.insert(cloud); array.display(); findPerson(array, "san"); findPerson(array, "kris"); array.delete(""); array.delete("ly"); array.delete("wu"); array.delete("si"); array.display(); } private static void findPerson(ClassDataArray array, String searchName) { if(array.find(searchName)!=null){ System.out.println("find "+ searchName);; } else{ System.out.println("can't find "+searchName); } } }