集合 set

概述

用于存储无序元素,值不能重复。

重构思路

  1. 添加时忽略重复元素
  2. 添加内部类,iterator
  3. implement iterable 后可以使用for each
  4. 重写equal,toString
  5. hashcode 暂时忽略

以下为generic构造
造轮子

1
2
3
4
5
6
7
8
9
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//implement iterable 后可以使用for each
public class ArraySet<T> implements Iterable<T>{
private T[] items;
private int size;

//返回通用iterator
public Iterator<T> iterator(){
return new ArraySetIterator();
}
//构建通用iterator
private class ArraySetIterator implements Iterator<T>{
private int index;
public ArraySetIterator(){
index = 0;
}

public boolean hasNext(){
return index < size;
}

public T next(){
T returnItem = items[index];
index++;
return returnItem;
}

}

public ArraySet(){
items = (T[]) new Object[100];
size = 0;
}

public boolean contains(T x){
for(int i = 0;i<size;i++){
if(x.equals(items[i])){
return true;
}
}
return false;
}

public void add(T x){
if(x == null){
throw new IllegalArgumentException("cannot add null yo the set");
}
if(contains(x)){
return;
}
items[size] = x;
size++;
}

public int size(){
return size;
}
//toString 重写
@Override
public String toString(){
String returnString = "{";
for(T item: this){
returnString += item.toString();
returnString += ", ";
return returnString;
}
returnString += items[size-1];
returnString += "}";
return returnString;
}

//Equals 重写
@Override
public boolean equals(Object other){
if(other == this){
return true;
}
if(other == null){
return false;
}

if(other.getClass() != this.getClass()){
return false;
}
ArraySet<T> o = (ArraySet<T>) other;
if(o.size() == this.size()){
return false;
}
for(T item: this){
if(!o.contains(item)){
return false;
}
}
return true;
}

public static void main(String[] args) {
ArraySet<Integer> a = new ArraySet<Integer>();
a.add(5);
a.add(10);
a.add(15);

Iterator<Integer> iterator = a.iterator();
while(iterator.hasNext()){
int i = iterator.next();
System.out.println(i);
}

for(int i : a){
System.out.println(i);
}
}
}
作者

黄港欢

发布于

2020-06-07

更新于

2021-03-15

许可协议