From 03f846c07ce4f1aca5c865f139f4ea45b6aa127f Mon Sep 17 00:00:00 2001 From: xiaojunhehe <43926569+xiaojunhehe@users.noreply.github.com> Date: Wed, 10 Oct 2018 19:46:02 +0800 Subject: [PATCH] =?UTF-8?q?=E9=92=88=E5=AF=B9=E4=B8=8A=E6=AC=A1=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E7=9A=84=E4=B8=80=E4=BA=9B=E9=94=99=E8=AF=AF=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E4=BF=AE=E6=AD=A3=E5=B9=B6=E4=B8=94=E5=9B=9E=E7=AD=94?= =?UTF-8?q?count=E7=9A=84=E4=BD=9C=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- java/05_array/Array.java | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/java/05_array/Array.java b/java/05_array/Array.java index 6b7ad05..8ec2fe1 100644 --- a/java/05_array/Array.java +++ b/java/05_array/Array.java @@ -11,14 +11,14 @@ public class Array { public int data[]; //定义数组长度 private int n; - //定义中保存的数据个数 + //定义中实际个数 private int count; //构造方法,定义数组大小 public Array(int capacity){ - this.data = new int[]{0,1,2,3,4}; + this.data = new int[capacity]; this.n = capacity; - this.count=capacity; + this.count=0;//一开始一个数都没有存所以为0 } //根据索引,找到数据中的元素并返回 @@ -49,13 +49,14 @@ public class Array { //向数组中插入一个元素 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]; + //当实际存储的个数等于数组的最大长度就不让新增 + 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=arr;*/ for (int i = count-1; i>=index; --i){ data[i+1] = data[i]; @@ -66,13 +67,15 @@ public class Array { } public boolean insertToTail(int value) { -// if (count == n) return false;不是太懂 + + //当实际存储的个数等于数组的最大长度就不让新增 + if (count == n) return false; //数组长度增加1 - int[] arr = new int[count+1]; + /*int[] arr = new int[count+1]; for (int i = 0; i < data.length; i++) { arr[i] = data[i]; } - data=arr; + data=arr;*/ data[count++] = value; return true; }