**
//person属性
**
public class Person {
int pId;
String pName;
int age;
public Person(int pId, String pName, int age) {
super();
this.pId = pId;
this.pName = pName;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Person [pId=" + pId + ", pName=" + pName + ", age=" + age + "]";
}
public int getpId() {
return pId;
}
public void setpId(int pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
**
//ArrayList写的DataBase
**
package com.pro.pr;
import java.util.ArrayList;
import javax.swing.text.StyledEditorKit.ForegroundAction;
public class DataBase {
ArrayList<Person> list =new ArrayList<Person>();//< >里面可以定义List类型
public void init() {
list.add(null);//不写的话后面输出会报出界(*)
list.add(0, new Person(1,"zs",12));
list.add(1, new Person(2,"ls",18));
list.add(2, new Person(3,"ww",32));
}
public void add(int id,String name,int age) {
for (int i = 0; i <=list.size(); i++) {
if(list.get(i)==null) {
list.add(i, new Person(id,name,age));
break;
}
}
}
public void output() {
for (Person person : list) {
if(person==null) {
break;
}else {
System.out.println(person);//写list.toString(),会并排
}
}
}
public void updata(int newId,String newName,int newAge) {
for (int i = 0; i < list.size(); i++) {
if(newId==list.get(i).getpId()) {
list.set(i, new Person(newId,newName,newAge));
break;
}
}
}
public void delete(int id) {
int n=0;
for (int i = 0; i < list.size(); i++) {
if(list.get(i).getpId()==id) {
n=i;
break;
}
}
list.remove(n);//ArrayLIst的remove方法可以直接删掉对应的数
}
}
//(*)ArrayList.add();
原码:public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
其中:ensureCapacityInternal 是动态调整容量大小的方法
当我调用add方法时直接在ArrayList最后面插入一个元素,也就说ArrayList集合其实是一个动态可变的数组。
再是NumDow;NumService;Test;