自定义List集合
1.数组实现
1.1构建ArrayList集合
[Java] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
public class ArrayList { //定义Object类型的数组 Object[] data ; //统计变量,用于统计数组元素的真实个数 int size; public ArrayList() { //初始化长度为10 this(10); } ArrayList(int length){ //通过构造方法指定数组的长度 data = new Object[length]; } //长度 public int getLength(){ return size; } //为了方便看效果,我们覆写toString()方法 //为了打印真实的数组内容,除去空余的默认值 @Override public String toString() { //构建一个新的数组,长度为size Object[] newdata = new Object[size]; //将data中的元素拷贝到新数组中 System.arraycopy(data, 0, newdata, 0, size); //利用Arrays类,将数组转换成字符串 return Arrays.toString(newdata); } //增 void add(Object obj){ //如果数组满了 if(size>=data.length){ //构建一个新的数组,容量默认增加10 Object[] newdata = new Object[data.length+10]; //将原来的数组内容拷贝到扩容后的数组中 System.arraycopy(data, 0, newdata, 0, size); } //将新增的元素添加在数组的末尾 data[size] = obj; //数组真实长度自增1 size++; } //查找指定索引处的元素; public Object getElementByIndex(int index){ if(index<0||index>size){ throw new ArrayIndexOutOfBoundsException("数组越界了,索引范围是:0~"+(size-1)); } return data[index]; } //查找指定元素第一次出现的索引 public int getFirstIndexByElement(Object obj){ for (int i = 0; i < size; i++) { if(obj.equals(data[i])){ return i; } } return -1;//没有找到 } //删除指定索引处的元素 public void deleteElementByIndex(int index){ if(index<0||index>size){ throw new ArrayIndexOutOfBoundsException("数组越界了,索引范围是:0~"+(size-1)); } System.arraycopy(data, index+1, data, index, size-index-1); size--; } //删除指定的第一个元素 public void deleteFirstElement(Object obj){ int index = getFirstIndexByElement(obj); System.out.println(index); deleteElementByIndex(index); } } |
2.链表实现
2.1LinkedList
2.1.1 构建节点
[Java] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
|
public class Node { //节点的数据域 Object data; //节点的next指针 Node next; //构造方法,将数据值保存到节点的数据域 public Node(Object data) { this.data = data; }} |
2.1.2构建链表集合
[Java] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
public class LinkedListDemo { //第一个节点 Node first; //覆写toString方法,格式化输出数据 @Override public String toString() { StringBuilder sb = new StringBuilder("["); //构建一个指针指向第一个节点 Node temp = first; //循环遍历链表 while(temp!=null){ //如果当前节点的next指针不为空,将节点的数据取出,拼接到字符串中 if(temp.next!=null){ sb.append(temp.data).append(","); }else{ //如果当前节点的next指针为空,将节点的数据取出,并拼接一个结束符号 sb.append(temp.data).append("]"); } //将指针后移一位 temp = temp.next; } return sb.toString(); } //增 void add(Object obj){ //将数据封装到节点对象中 Node node = new Node(obj); |

浙公网安备 33010602011771号