数组
数组
有序的元素序列,Java的数组用于存储固定大小的多个同类型的元素。
数组方法及实现
成员变量及构造函数
Class Array<E>{
private E[] data;// 存放数据的集合
private int size;//有效元素个数
public Array(){
data = (E[])new Object[10];
size=0;
}
public Array(int capacity){
data=(E[])new Object[capacity];
size=0;
}
}
查询
toString()打印
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(String.format("Array:size=%d,capacity = %d\n",size,data.length))
sb.append('[');
for(int i =0;i<size;i++){
sb.append(data[i]);
if(i!=size-1){sb.append(",")}
}
sb.append(']');
return sb.toString;
}
查询有效元素个数
public int getSize(){
return size;
}
查询容量
public int getCapacity(){
return data.length;
}
数组是否为空
public boolean isEmpaty(){
return size==0;
}
查询Index索引位置的元素
public E get(int index){
if(index<0||index>=size){
throw new IllegalArgumentException("参数不合法");
}
retun data[index];
}
查询数组中是否有元素
public boolean contains(E.e){
for(int i=0;i<size;i++){
if(data[i].equals(e)){
return true;
}
}
return false;
}
查询数组中元素e的索引,如果不存在元素e,则返回-1
public int contains(E e){
for(int i=0;i<size;i++){
if(data[i].equals(e)){
return i;
}
}
return -1;
}
修改
修改Index索引下的元素为e
public void set(E,e){
if(index < 0 || index >= size){
throw new IllegalArgumentException("参数不合法");
}
data[index] = e;
}
添加元素
添加元素会涉及到容量的扩展,所以会有grow()方法来进行容量的变化
public void grow(int capacity){
E[] newData = (E[]) new Object(capacity);
for(int i=0;i<sizep;i++){
newData[i] =data[i];
}
data = newData;
}
元素添加
public void add(int index,E e){
if(index < 0 || index >= size){
throw new IllegalArgumentException("参数不合法");
}
if(size==data.length){grow(2*data.length)}
//index索引及后面的值都向后移动
for(int i = size-1;i>=index;i--){
data[i+1]=data[i]
}
data[index] = e;
size++;
}
首部添加
public void addFirst(E,e){
add(0,e);
}
元素尾部添加
public void addLast(E,e){
add(size,e);
}
删除
删除index索引的元素,并返回删除元素
public E remove(int index){
if(index < 0 || index >= size){
throw new IllegalArgumentException("参数不合法");
}
E removeE = data[index];
for(int i=index+1;i<size;i++){
data[i-1]=data[i];
}
size--;
if(size==(data.length/4)&&data.length/2!=0){
grow(data.length/2);
}
return removeE;
}
删除首部元素
public E removeFirst(){remove(0)}
删除尾部元素
public E removeLast(){remove(size-1)}
数据作为基本数据结构之一,基本的方法思想在后面数据结构都会有类似的体现。
注:由于现在笔者也是一个复习且刚开始写博客的过程,所以中间的代码都是直接在编辑器中写的以加强记忆。过程中可能有字母错误及排版问题的。见谅。日后改进
gitHub源码:数组

浙公网安备 33010602011771号