赞
踩
public class Array {
// 定义数组变量,data.length表示数组容量capacity
private int[] data;
// 定义数组中存放数据大小
private int size;
// 有参构造方法,传入数组的容量capacity构造动态数组
public Array(int capacity) {
data = new int[capacity];
size = 0;
}
// 无参构造方法,默认初始容量为capacity=10
public Array(){
this(10);
}
// 获取数组中元素个数
public int getSize(){
return size;
}
// 获取数组的容量
public int getCapacity(){
return data.length;
}
// 判断数组是否为空
public boolean isEmpty(){
return size == 0;
}
// 在数组末尾添加元素
public void addLast(int e){
if(size == data.length)
throw new IllegalArgumentException("AddLast failed.Array is full.");
data[size] = e;
size ++;
}
}
public class Array { // 定义数组变量,data.length表示数组容量capacity private int[] data; // 定义数组中存放数据大小 private int size; // 有参构造方法,传入数组的容量capacity构造动态数组 public Array(int capacity) { data = new int[capacity]; size = 0; } // 无参构造方法,默认初始容量为capacity=10 public Array() { this(10); } // 获取数组中元素个数 public int getSize() { return size; } // 获取数组的容量 public int getCapacity() { return data.length; } // 判断数组是否为空 public boolean isEmpty() { return size == 0; } // 在数组末尾添加元素 public void addLast(int e) { if (size == data.length) throw new IllegalArgumentException("AddLast failed.Array is full."); data[size] = e; size++; } // 数组指定位置添加元素 public void add(int index, int e) { if (size == data.length) throw new IllegalArgumentException("Add failed.Array is full."); if (index < 0 || index > size) throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size"); for (int i = size - 1; i >= index; i--) data[i + 1] = data[i]; data[index] = e; size++; } }
public class Array { // 定义数组变量,data.length表示数组容量capacity private int[] data; // 定义数组中存放数据大小 private int size; // 有参构造方法,传入数组的容量capacity构造动态数组 public Array(int capacity) { data = new int[capacity]; size = 0; } // 无参构造方法,默认初始容量为capacity=10 public Array() { this(10); } // 获取数组中元素个数 public int getSize() { return size; } // 获取数组的容量 public int getCapacity() { return data.length; } // 判断数组是否为空 public boolean isEmpty() { return size == 0; } /* // 在数组末尾添加元素 public void addLast(int e) { if (size == data.length) throw new IllegalArgumentException("AddLast failed.Array is full."); data[size] = e; size++; }*/ // 在数组末尾添加元素(复用add方法) public void addLast(int e) { add(size, e); } // 在数组头部添加元素(复用add方法) public void addFirst(int e) { add(0, e); } // 数组指定位置添加元素 public void add(int index, int e) { if (size == data.length) throw new IllegalArgumentException("Add failed.Array is full."); if (index < 0 || index > size) throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size"); for (int i = size - 1; i >= index; i--) data[i + 1] = data[i]; data[index] = e; size++; } }
如果感兴趣的童鞋,可以观看我下一篇博客:数组中查询元素和修改元素
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。