class Person
{
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
class PersonArray
{
private int nElems;
private Person[] arr;
PersonArray(int size){
arr= new Person[size];
nElems=0;
}
//----insert------
public void insert(String name,int age){
arr[nElems]=new Person(name,age);
nElems++;
}
//----delete-----
public void delete(String name){
int i;
for(i=0;i<nElems;i++){
if (arr[i].getName().equals(name))
break;
}
for(int k=nElems;i<k;k--)
arr[k-1]=arr[k];
nElems--;
}
//----find-------
public int find(String name){
for(int i=0;i<nElems;i++){
if (arr[i].getName().equals(name))
return i;
}
return -1;
}
//-----print-----
public void print(){
for(int i=0;i<nElems;i++)
System.out.println("arr["+i+"]="+arr[i].getName()+":"+arr[i].getAge());
}
}
class PersonArrayDemo
{
public static void main(String[] args)
{
int maxSize=100;
PersonArray arr= new PersonArray(maxSize);
arr.insert("a1",11);
arr.insert("a2",12);
arr.insert("a3",13);
arr.insert("a4",14);
arr.print();
System.out.println("find a3:"+arr.find("a3"));
arr.delete("a4");
arr.print();
}
}
【DataStructure&AlgorithmInJava】Ch02-PersonArrayDemo
最新推荐文章于 2022-05-11 08:22:38 发布