ArrayList代理类

package com.svse.myapp;

import java.util.Arrays;
import java.util.Random;
import org.junit.Test;

public class MyArrayList {
	private Object[] objs = null;
	private int index = 0;

	public MyArrayList() {
		objs = new Object[10];
	}
	// public MyArrayList(int i) {
	// objs = new Object[i];
	// }

	@Test
	public void myTest() {
		MyArrayList myArrayList = new MyArrayList();
		Random random = new Random();
		for (int i = 0; i < 21; i++) {
			myArrayList.add(random.nextInt(50));
		}

		System.out.println(myArrayList.indexOf(6));
		myArrayList.printList();
	}

	public void add(Object obj) {
		if (index == objs.length) {
			this.objs = Arrays.copyOf(objs, index * 2);// System.arraycopy();
		}
		objs[index++] = obj;
	}

	public boolean delete(int index) {
		if (index > this.index)
			return false;
		for (int i = index; i < this.index; i++) {
			objs[i] = objs[i + 1];
		}
		this.index--;
		return true;
	}

	public boolean set(int index, Object e) {
		return this.index >= index ? true : false;
	}

	public void printList() {
		for (int i = 0; i < index; i++) {
			if (i % 5 == 0)
				System.out.println();
			System.out.print("objs[" + i + "] == " + objs[i] + ",\t");
		}
	}

	public int indexOf(Object e) {
		this.sort();// 使用二分法查找法,数组必须是有序且无重复的
		int low = 0, height = this.index, middle;
		while (low <= height) {
			middle = (low + height) >> 1;
			if ((int) e > (int) objs[middle])
				low = ++middle; // 高半区查找
			else if ((int) e < (int) objs[middle])
				height = --middle;// 低半区查找
			else
				return middle;
		}
		return -1;
	}

	public void sort() {
		for (int i = 0; i < this.index - 1; i++) {
			for (int j = i + 1; j < this.index; j++) {
				if ((int) this.objs[i] > (int) this.objs[j])
					swap(i, j);
			}
		}
	}

	private void swap(int i, int j) {
		Object temp;
		temp = this.objs[i];
		this.objs[i] = this.objs[j];
		this.objs[j] = temp;
	}

	public boolean isContains(Object obj) {
		return indexOf(obj) != -1;
	}

	public int count() {
		return this.index;
	}

}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值