-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImmutableQueue.java
69 lines (48 loc) · 1.49 KB
/
ImmutableQueue.java
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
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public final class ImmutableQueue<T> implements Queue<T> {
private final List<T> queue;
private int size;
ImmutableQueue(int size)
{
if(size<=0){
throw new IllegalArgumentException("Queue size must be greater than 0");
}
this.size = size;
queue = new LinkedList<T>();
}
private ImmutableQueue(List<T> newList){
queue = Collections.unmodifiableList(new LinkedList<T>(newList));
}
@Override
public Queue<T> enQueue(T t){
if(null == t){
throw new IllegalArgumentException("Value is null");
}
if(queue.size()== this.size){
throw new IllegalArgumentException("Queue is full");
}
List<T> newList = new LinkedList<T>(queue);
newList.add(t);
ImmutableQueue<T> newQueue = new ImmutableQueue<T>(newList);
return newQueue;
}
@Override
public Queue<T> deQueue(){
if (queue.size() == 0){
throw new IllegalArgumentException("Queue size is empty");
}
List<T> tmpList = new LinkedList<>(queue);
ImmutableQueue<T> newQueue = new ImmutableQueue<>(tmpList.subList(1,tmpList.size()));
return newQueue;
}
@Override
public T head(){
return queue.size()>0 ? queue.get(0):null;
}
@Override
public boolean isEmpty(){
return queue.size()==0?true:false;
}
}