您定义的n和count没有看懂,而且调用过程中产生角标越界异常,我使用的JDK是1.8。自己私下改了代码,加了注释,希望能给您的开源项目做贡献。

This commit is contained in:
xumorden 2018-10-07 11:32:14 +08:00
parent 576940cf11
commit 62a07df093

View File

@ -7,53 +7,83 @@ package array;
* Author: Zheng
*/
public class Array {
private int data[];
private int n;
private int count;
//定义整型数据data保存数据
public int data[];
//定义数组长度
private int n;
//定义中保存的数据个数
private int count;
public Array(int capacity) {
data = new int[capacity];
n = capacity;
count = 0;
}
public int find(int index) {
if (index < 0 || index >= count ) return -1;
return data[index];
}
public boolean delete(int index) {
if (index < 0 || index >= count) return false;
for(int i = index + 1; i < count; ++i) {
data[i-1] = data[i];
//构造方法定义数组大小
public Array(int capacity){
this.data = new int[]{0,1,2,3,4};
this.n = capacity;
this.count=capacity;
}
--count;
return true;
}
public boolean insert(int index, int value) {
if (index < 0 || index >= count) return false;
if (count == n) return false;
for (int i = count - 1; i >= index; --i) {
data[i+1] = data[i];
//根据索引找到数据中的元素并返回
public int find(int index){
if (index<0 || index>=count) return -1;
return data[index];
}
data[index] = value;
++count;
return true;
}
public boolean insertToTail(int value) {
if (count == n) return false;
data[count++] = value;
return true;
}
//根据索引删除数组中元素
public boolean delete(int index){
if (index<0 || index >=count) return false;
//从删除位置开始将后面的元素向前移动一位
for (int i=index+1; i<count; ++i){
data[i-1] = data[i];
}
//删除数组末尾元素 这段代码不需要也可以
/*int[] arr = new int[count-1];
for (int i=0; i<count-1;i++){
arr[i] = data[i];
}
this.data = arr;*/
public void printAll() {
for (int i = 0; i < count; ++i) {
System.out.print(data[i] + " ");
--count;
return true;
}
System.out.println();
}
//向数组中插入一个元素
public boolean insert(int index, int value){
if (index<0 || index>=count) return false;
// if (count == n) return false;不是太懂
//数组长度增加1
int[] arr = new int[count+1];
for (int i = 0; i < data.length; i++) {
arr[i] = data[i];
}
data=arr;
for (int i = count-1; i>=index; --i){
data[i+1] = data[i];
}
data[index] = value;
++count;
return true;
}
public boolean insertToTail(int value) {
// if (count == n) return false;不是太懂
//数组长度增加1
int[] arr = new int[count+1];
for (int i = 0; i < data.length; i++) {
arr[i] = data[i];
}
data=arr;
data[count++] = value;
return true;
}
public void printAll() {
for (int i = 0; i < count; ++i) {
System.out.print(data[i] + " ");
}
System.out.println();
}
}