关于数组的基本数据类型和引用类型
首先,JAVA数据类型分为基本数据类型与引用类型
如果你声明的是基本数据类型的数组,那各元素都是基本数据类型,不是对象 比如 :int[] a = new int[3];
如果你声明的是引用类型的数组,那各元素都是对象 比如:Object[] test = new Object[12];
package com.myCollection;
import java.util.Arrays;
/**
*
* 模拟JDK ArrayList
* @author mdeng
*
*/
public class MyArrayList {
/**
* The value is used for object storage.
*/
private Object [] value;
/**
* The size is the number of object used.
*/
private int size;
public MyArrayList(){
//value = new Object[2];
this(16);
}
public MyArrayList(int size){
value = new Object[size];
}
// int[] a = new int[3];
// Object[] test = new Object[12];
public void add(Object obj){
value[size]=obj;
size++;
//当size>16,执行扩容,以下为经典扩容代码。
if(size>=value.length){
int newCapacity = value.length*2;
Object[] newList = new Object[newCapacity];
//System.arraycopy(src, srcPos, dest, destPos, length);
for (int i=0; i<value.length; i++){
newList[i]=value[i];
}
value=newList;
}
}
public int length(){
return value.length;
}
public int size(){
return size;
}
public Object get(int index){
if (index<0||index>size-1)
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value[index];
}
public int indexOf(Object obj){
if(obj==null){
return -1;
}else{
for(int i=0;i<value.length;i++){
if(obj==value[i]){
return i;
}
}
return -1;
}
}
public static void main(String[] args) {
MyArrayList me = new MyArrayList();
me.add("111");
me.add("111");
me.add("111");
me.add("111");
me.add("111");
me.add(new Human("邓善军"));
Human man = (Human)me.get(5);
System.out.println(man.getName());
System.out.println(me.size());
System.out.println(me.indexOf(man));
}
}