// 主要功能有增、删(根据索引,根据值)、改、查扩容
1 package com.yw.flink;
2
3 public class Test2 {
4
5 public static void main(String[] args) throws Exception {
6 Mylist s = new Mylist();
7 s.insert(1);
8 s.insert(2);
9 s.insert(1);
10 System.out.println(s);
11 s.deleteByIndex(0);
12 s.travel();
13 }
14 }
1 package com.yw.flink;
2
3 // 主要功能有增、删(根据索引,根据值)、改、查扩容
4 public class Mylist {
5 private int[] array = null;
6 //数组有效长度
7 public int length = 0;
8
9 //空参构造函数,默认数组大小为10
10 public Mylist() {
11 this.array = new int[10];
12 }
13
14 public Mylist(int size) {
15 this.array = new int[size];
16 }
17
18 //给自定义数组添加元素
19 public void insert(int number) {
20 //判断数组是否满
21 //满了,扩容,扩容需要新建一个数组,将旧的数据复制过去,再插入
22 //没满,直接插入
23 //插入之后length+1
24 if (length == array.length) {
25 expand(this.array);
26 array[length] = number;
27 } else {
28 this.array[length] = number;
29 }
30 length++;
31
32 }
33
34 //每次扩容后比之前大一倍
35 public void expand(int[] arr) {
36 int expandSize = arr.length * 2;
37 this.array = new int[expandSize];
38
39 for (int i = 0; i < arr.length; i++) {
40 this.array[i] = arr[i];
41 }
42 }
43
44 //根据索引删除元素
45 public void deleteByIndex(int index) throws Exception {
46 //判断索引是否越界,即超过了有效长度
47 //超过了,抛出异常提示
48 //没超过就删除
49 //首先需要将该索引之后的所有元素前移一个位置。
50 //最后length-1
51 if (index > length - 1 || index < 0) {
52 throw new Exception("删除时索引越界");
53 } else {
54 for (int i = index; i < length; i++) {
55 array[i] = array[i + 1];
56 }
57 length--;
58 }
59 }
60
61 //根据值删除元素,删除多个
62 public void deleteByValue(int value) throws Exception {
63 //首先看数组中有没有这个值,没有抛异常提示
64 boolean flag = false;
65 for (int i = 0; i < length; i++) {
66 if (array[i] == value) {
67 flag = true;
68 deleteByIndex(i);
69 }
70 }
71 if (!flag)
72 throw new Exception("该元素不存在");
73 deleteOne(value);
74
75 }
76
77 //删除一个元素
78 public void deleteOne(int value) throws Exception {
79 boolean flag = false;
80 for (int i = 0; i < length; i++) {
81 if (array[i] == value) {
82 flag = true;
83 deleteByIndex(i);
84 break;
85 }
86 }
87 if (!flag)
88 throw new Exception("该元素不存在");
89 }
90
91 //修改某索引对应元素的值
92 public void update(int index, int value) throws Exception {
93 if (index > length - 1 || index < 0) {
94 throw new Exception("修改时索引越界");
95 } else {
96 array[index] = value;
97 }
98 }
99
100 //(遍历)数组的元素
101 public void travel() {
102 System.out.print("[");
103 for (int i = 0; i < length; i++) {
104 System.out.print(array[i]);
105 if (i < length - 1)
106 System.out.print(",");
107 }
108 System.out.println("]");
109 }
110
111 //根据值查找元素,返回索引
112 public int search(int value) throws Exception {
113 int i = 0;
114 for (i = 0; i < length; i++) {
115 if (value == array[i])
116 break;
117 }
118 if (i == length)
119 return -1;
120 return i;
121 }
122
123 //根据索引元素,返回值
124 public int searchByIndex(int index) throws Exception {
125 if (index < 0 || index >= length) {
126 throw new Exception("索引越界");
127 }
128 return array[index];
129
130 }
131
132
133
134 }