您的位置:首页 > 编程语言 > Java开发

数组第二十四课,模拟ArrayList容器的底层实现,JDK源码分析

2015-02-26 15:50 645 查看
package com.pkushutong.MyCollection;
/**
* 模拟实现JDK中提供的ArrayList类
* @author dell
*
*/
public class MyArrayList {
/**
* The value is used for Objects storage.
*/
private Object[] value;

/**
* The size is the number of Objects used.
*/
private int size;

public MyArrayList(){
//value = new Object[16];
this(10);
}

//重载构造方法
public MyArrayList(int size){
if(size < 0){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
value = new Object[size];
}

//返回添加方法里的条目数量
public int size(){
return size;
}

//返回条目数量是否为空
public boolean isEmpty() {
return size == 0;
}

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 void add(Object obj){
value[size] = obj;
size++;
if(size >= value.length){
//装不下了,扩容吧
int newCapacity = value.length * 2;
Object[] newList = new Object[newCapacity];

for(int i = 0; i < value.length; i++){
newList[i] = value[i];
}
value = newList;
}
}

public Object get(int index){
if(index < 0 || index > size - 1){	//0到size-1之间
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
return value[index];
}

public int lastIndexOf(Object obj) {
if (obj == null) {
return -1;
} else {
for (int i = value.length-1; i >= 0; i--)
if (obj==value[i])
return i;
}
return -1;
}

public Object set(int index, Object obj) {
if(size < 0){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
Object old = value[index];
value[index] = obj;
return old;
}

public static void main(String[] args) {
MyArrayList list = new MyArrayList(2);
list.add("abcde");
list.add(new Human("樊"));

Human h = (Human) list.get(1);
System.out.println(h.getName());

//System.out.println(list.get(0));
System.out.println(list.size());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐