一、数组介绍
二、Java中使用数组
- 第一种:声明数组的时候初始化,有N个元素:
数组类型 [] 数组名 = {em1,em2,em3,…,emN};
int[] array = {1,2,3,4,6,5};
- 2、用new关键字声明数组的同时指定数组长度:
数组类型[] 数组名 = new 数组类型[N];
String[] str = new String[6];
- 3、用new关键字声明数组的同时初始化数组:
数组类型[] 数组名 = new 数组类型[] {em1,em2,em3,…,emN};
int[] array = new int[] {2,4,7,6,8,9};
- 数组一旦声明,数组长度就已经确定。每个数组都有一个length属性,不可改变。可以改变数组元素
三、实现ArrayList
public class MyArray<E> {
private int size = 0;
private static final int CAPACITY = 10;
private static final int NOT_FOUND = -1;
private E[] elements = (E[]) new Object[CAPACITY];
public MyArray() {
this(CAPACITY);
}
public MyArray(int capacity) {
if (capacity < 10) {
elements = (E[]) new Object[CAPACITY];
} else {
elements = (E[]) new Object[capacity];
}
}
}
判断当前数组是否为空
public boolean isEmpty() {
return size == 0;
}
是否包含某个元素
public boolean contains(E element) {
return indexOf(element)!=ELEMENT_NOT_FOUND;
}
查找元素
public int indexOf(E element) {
if(element==null){
for (int i = 0; i <size; i++) {
if(elements[i]==null){
return i;
}
}
}else{
for (int i = 0; i <size; i++) {
if(element.equals(elements[i])){
return i;
}
}
}
return NOT_FOUND;
}
返回对应索引的值
public E get(int index) {
checkIndex(index);
return elements[index];
}
设置index位置元素的值
public E set(int index, E element) {
checkIndex(index);
E old=elements[index];
elements[index]=element;
return old;
}
清空所有元素
public void clear() {
for (int i = 0; i <size; i++) {
elements[i]=null;
}
size=0;
}
返回当前元素的数量
public int size() {
return size;
}
添加元素到尾部
public void add(E element) {
if(size>elements.length-1){
ensureCapacity(size+1);
}
elements[size]=element;
size++;
}
向index位置添加元素
public void add(int index, E element) {
if(index<0||index>size){
throw new IndexOutOfBoundsException("索引越界");
}
for (int i =size; i>index; i--) {
elements[i]=elements[i-1];
}
elements[index]=element;
size++;
}
移除index位置元素
public E remove(int index) {
checkIndex(index);
E old=elements[index];
for (int i = index; i <size; i++) {
elements[i]=elements[i+1];
}
size--;
elements[size]=null;
if(size==elements.length>>1){
ensureCapacity(elements.length>>1);
}
return old;
}
返回元素集合
@Override
public String toString() {
StringBuilder sb = new StringBuilder("size:" + size + " => [");
for (int i = 0; i < size; i++) {
if (i != 0) {
sb.append(" ,");
}
sb.append(elements[i]);
}
sb.append("]");
return sb.toString();
}
判断是否越界
public void checkIndex(int index){
if(index<0||index>=size){
throw new IndexOutOfBoundsException("索引越界");
}
}
确保数组容量
public void ensureCapacity(int capacity){
if(elements.length>=capacity){
return;
}
E[] newElments=(E[])new Object[elements.length+(elements.length>>1)];
for (int i = 0; i <size; i++) {
newElments[i]=elements[i];
}
elements=newElments;
}
|