数组如何存储对象?
数组不仅可以存储基本数据类型的数据,还可以存储对象类型,使用起来非常方便。下面直接给出数组存储对象的方法:
- 首先需要创建一个对象类,这里一Person类为例:
package arrayapplication;
/**
* 数组存储对象Person类
* @author 磊大大
*/
public class Person {
private String lastName;
private String firstName;
private int age;
//构造方法
public Person(String lastName, String firstName, int age){
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
}
//显示
public void displayPerson(){
System.out.print("FirstName:"+firstName);
System.out.print(", LastName:"+lastName);
System.out.print(", age:"+age);
System.out.println();
}
//获取lastName
public String lastName(){
return lastName;
}
}
2、创建一个数组类,封装对象数组的功能(增、删、查):
package arrayapplication;
/**
* 数组存储对象类型
* @author 磊大大
*/
public class ArrayBub {
Person[] a ; //声明一个对象数组
private int nElems; //数组大小
private int j; //循环变量
public ArrayBub(int max){
a = new Person[max];
nElems=0;
}
//查找
public Person find(String searchName){
for(j = 0; j<nElems; j++)
if(a[j].lastName().equals(searchName)) break;
if(j == nElems)
return null;
else{
return a[j];
}
}
//添加
public void insert(String lastName, String firstName, int age){
a[nElems] = new Person(lastName, firstName, age);
nElems++;
}
//显示所有
public void displayAll(){
for(j =0; j<nElems; j++)
a[j].displayPerson();
}
//删除
public boolean delete(String searchName){
for(j = 0; j<nElems; j++)
if(a[j].lastName().equals(searchName)) break;
if(j==nElems)
return false;
else{
for(int k =j;k<nElems;k++)
a[k]=a[k+1];
nElems--;
}
return true;
}
}
3、创建一个入口类:
package arrayapplication;
/**
* 数组存储对象入口
* @author 磊大大
*/
public class ArrayBubApp {
public static void main(String[] args){
String searchName;
ArrayBub arr = new ArrayBub(10);
arr.insert("Tom", "toom", 12);
arr.insert("Tom1", "toom1", 18);
arr.insert("Tom2", "toom2", 18);
arr.insert("Tom3", "toom3", 18);
arr.displayAll();
searchName="Tom1";
if(arr.find(searchName)!=null)
System.out.println("Found:"+searchName);
else
System.out.println("Can't find:"+searchName);
if(!arr.delete(searchName))
System.out.println("Can't find:"+searchName+",so can't delete");
else
System.out.println("Delete Success!");
arr.displayAll();
}
}
是不是发现数组的功能优点强大呢?不仅可以存储基本数据,还可以存储对象类型的数据。
下一篇文章讲讲数组的排序方法