数组_存储对象

public class Person {
    private String lastName;
    private String firstName;
    private int age;
    public Person(String last,String first,int a) {
        lastName=last;
        firstName=first;
        age=a;
    }
    public void displayPerson() {
        System.out.print("last name:"+lastName);
        System.out.print(",first name"+firstName);
        System.out.println(",age:"+age);
    }
    public String getLast() {
        return lastName;
    }

}
public class ClassDataArray {
    private Person[] a;
    private int nElems;
    public ClassDataArray(int max) {
        a=new Person[max];
        nElems=0;
    }
    //查找(根据姓查找)
    public Person find(String searchName) {
        int j;
        for(j=0;j<nElems;j++)
            if(a[j].getLast().equals(searchName))
                break;
        if(j==nElems)
            return null;
        else
            return a[j];
    }
    public void insert(String last,String first,int age) {
        a[nElems++]=new Person(last, first, age);
    }
    //按姓删除
    public boolean delete(String searchName) {
        int j;
        for(j=0;j<nElems;j++)
            if(a[j].getLast().equals(searchName))
                break;
        if(j==nElems)
            return false;
        else 
            for(int k=j;k<nElems;k++)
                a[k]=a[k+1];
            nElems--;
            return true;        
    }
    public void displayA() {
        for(int j=0;j<nElems;j++)
            a[j].displayPerson();
    }

}
public class Test {

    public static void main(String[] args) {
        int maxSize=100;
        ClassDataArray array=new ClassDataArray(maxSize);
        array.insert("Evans", "Patty", 24);
        array.insert("Smith", "Lorraine", 37);
        array.insert("Yee", "Tom", 43);
        array.insert("Adams", "Henry", 63);
        array.insert("Hashimoto", "Sato", 21);
        array.insert("Stimson", "Henry", 29);
        array.insert("xiao", "ming", 72);
        array.insert("huang", "rong",54 );
        array.insert("liu", "qian", 22);
        array.displayA();
        Person found=array.find("huang");
        if(found!=null) {
            System.out.println("找到了");
            found.displayPerson();
        }else
            System.out.println("没有找到");
        array.delete("huang");
        array.delete("liu");
        array.displayA();

    }

}

 

posted @ 2017-12-22 10:50  S-Mustard  阅读(324)  评论(0编辑  收藏  举报