1、Eg:
Dog [] d = new Dog[1];
Dog d1 = new Dog();
d[0]=d1; //d1指向d0所指向的地址
d[0].setName(“旺财”);
2.arrcopy方法
public static void arraycopy(Object src, (源数组)
int srcPos,(源数组中的起始位置)
Object dest,(目的数组)
int destPos,(目标数据中的起始位置)
int length)(复制长度)
从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。从 src 引用的源数组到 dest 引用的目标数组,数组组件的一个子序列被复制下来。被复制的组件的编号等于 length 参数。源数组中位置在 srcPos 到 srcPos+length-1 之间的组件被分别复制到目标数组中的 destPos 到 destPos+length-1 位置。
3.数组扩容问题。
问题提出:申请一个一定长度的数组,若数组存满数据怎么解决问题?
解决思路:重新申请比之前长度更长的数组,然后将以前数组的内容copy过来,然后再继续存数据,但是这样一次次的申请太浪费时间,因此申请数组时,长度为以前数组的1.5倍,若以后不够了再次申请,这样就可以节省时间。
Eg2:
public class Vector {
private Object[] objs = null;
private int index = 0;
public void addAll(Object[] objs) {
for (Object object : objs) {
add(object);
}
}
public void add(Object obj) {
// 判断是不是第一次来
if (objs == null) {
objs = new Object[5];
objs[0] = obj;
index++;
} else {
// 判断长度够不够了
if (index == objs.length) {
//申请一个比以前多0.5的容器
Object[] objs1 = new Object[(int) (objs.length * 1.5)];
System.arraycopy(objs, 0, objs1, 0, objs.length);
// Arrays.c
objs = objs1;
}
///把数据 交给最后一个
objs[index] = obj;
index++;
}
}
public int size() {
return index;
}
public Object get(int index) throws IndexOutOfBoundsException {
if (index >= this.index) {
throw new IndexOutOfBoundsException(index + "");
}
return objs[index];
}
public void remove(int i) throws IndexOutOfBoundsException {
// 判断你要删除的下标在不在我的范围内
if (i >= index || i < 0) {
throw new IndexOutOfBoundsException(index + "");
}
// Object objs1=new Object();
// 判断要不要缩容
if ((objs.length / (float) (index)) > 2.1F) {
// 按现在的存储个数 *
Object[] objs1 = new Object[(int) (index * 1.1)];
// 拷贝 把老数据导入到新数组里
System.arraycopy(objs, 0, objs1, 0, index);
objs = objs1;
}
// 删除一个
System.arraycopy(objs, i + 1, objs, i, objs.length - i - 1);
index--;
}
}
4.Vector
Vector 类可以实现可增长的对象数组。与数组一样,它包含可以使用整数索引进行访问的组件。但是,Vector 的大小可以根据需要增大或缩小,以适应创建 Vector 后进行添加或移除项的操作
Vector的方法:
add
public boolean add(E e)
将指定元素添加到此向量的末尾。
addAll
public boolean addAll(Collection<? extends E> c)
将指定 Collection 中的所有元素添加到此向量的末尾,按照指定 collection 的迭代器所返回的顺序添加这些元素。如果指定的 Collection 在操作过程中被修改,则此操作的行为是不确定的(这意味着如果指定的 Collection 是此向量,而此向量不为空,则此调用的行为是不确定的)。