package DataDtructure;
import java.util.ArrayList;
/**
* ClassName: Array
* Company:华中科技大学电气学院
* date: 2019/8/20 22:33
* author: YEXIN
* version: 1.0
* since: JDK 1.8
* Description:数组
*/
public class Array<E> {
private int size;//实际数组元素个数,size=0,表示数组为空
private E[] data;
//capacity是数据容量
public Array(int capacity){
data = (E[])new Object[capacity];//!!!!!!!!!!!!!!!
size = 0;
}
//默认容量
public Array(){
this(10);
}
public int getSize(){
return size;
}
public int getCapacity(){
return data.length;
}
public boolean isEmpty(){
return size == 0;
}
//向指定位置插入新的元素
public void add(int index, E e){
if(index < 0 || index > size){
throw new IllegalArgumentException("index:>=0,and index <= size");
}
//扩容
if(size == data.length){
resize(2*data.length);
}
for(int i = size - 1;i >= index;i --){
data[i+1] = data[i];
}
data[index] = e;
size ++;
}
private void resize(int newCapacity){
E[] newdata = (E[])new Object[newCapacity];
for(int i = 0;i < size;i++){
newdata[i] = data[i];
}
data = newdata;
}
//在最后一个位置插入
public void addLast(E e){
add(size,e);
}
//在头插入元素
public void addFirst(E e){
add(0,e);
}
//获取index位置的元素
public E get(int index){
if(index < 0 || index >= size){
throw new IllegalArgumentException("Get failed , index is illegal");
}
return data[index];
}
//修改某个位置的元素
public void set(int index,E e){
if(index < 0 || index >= size){
throw new IllegalArgumentException("Get failed , index is illegal");
}
data[index] = e;
}
//查找数组中是否含有某个元素
public boolean contains(E e){
for(int i = 0; i < size; i++){
if(data[i].equals(e)){
return true;
}
}
return false;
}
//查找某个元素的索引
public ArrayList find(E e){
ArrayList<Integer> arr = new ArrayList<>();
for(int i = 0; i < size; i++){
if(data[i].equals(e)){
arr.add(i);
}
}
return arr;
}
//删除数组中的某个位置的元素
public E remove(int index){
if(index < 0 || index >= size){
throw new IllegalArgumentException("Remove failed , index is illegal");
}
E res = data[index];
for(int i = index +1 ; i < size ; i++){
data[i-1] = data[i];
}
size --;
data[size] = null;//loitering objects
//容器收缩
if(size == data.length/3 && data.length / 2 != 0){//避免震荡
resize(data.length/2);
}
return res;
}
public E removeFirst(){
return remove(0);
}
public E removeLast(){
return remove(size-1);
}
//删除某个元素
public void removeElement(E e){
ArrayList<Integer> indexArray = find(e);
for(Integer i : indexArray) {
remove(i);
}
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Array:size = %d,capacity = %d\n", size,data.length));
res.append('[');
for(int i = 0 ;i < size; i++){
res.append(data[i]);
if(i != size - 1){
res.append(",");
}
}
res.append("]");
return res.toString();
}
}
java实现数据结构---数组
最新推荐文章于 2023-06-10 16:01:43 发布