数组存储对象

Person类数组

package ch01;

public class TestPersonArray {

	public static void main(String[] args) {
	    PersonArray pa=new PersonArray();
	    
	    //创建对象
	    Person p1=new Person("张三", 20, "男");
	    Person p2=new Person("李四", 21, "男");
	    Person p3=new Person("王五", 22, "女");
	    Person p4=new Person("赵六", 23, "男");
	    Person p5=new Person("李斯", 25, "男");
	    
	    //插入操作
	    pa.insert(p1);
	    pa.insert(p2);
	    pa.insert(p3);
	    pa.insert(p4);
	    pa.insert(p5);
	    
	    pa.display();
	    
	    //删除操作
	    pa.delete(p4);
	    pa.display();
	    
	    pa.delete("李斯");
	    pa.display();
	    
	    //修改操作
	    Person newPerson=new Person("赵娇娇", 24, "女");
	    pa.change(p1,newPerson);
	    pa.display();

	}

}


package ch01;

public class PersonArray {
	//数组
	private Person[] arr;
	
	//数组中有效数据的大小
	private int elems;
	
	//默认构造函数
	public PersonArray(){
		arr=new Person[50];
	}

	public PersonArray(int max) {
		arr=new Person[max];
	}

	//插入数据
	public void insert(Person person) {
		arr[elems]=person;
		elems++;
		
	}

	//显示数据
	public void display() {
	   for(int i=0;i



package ch01;

public class Person {
   //用户姓名
	private String name;
	
	//用户年龄
	private int age; 
	
	//用户性别
	private String sex;
	
	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 String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Person(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}


    public void display(){
    	System.out.print("姓名"+this.name);
    	System.out.print("年龄"+this.age);
    	System.out.print("性别"+this.sex);
    	System.out.println();
    }
	
	
	

	

}

经典person类

你可能感兴趣的:(数组)