-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathStandardIterator.java
81 lines (72 loc) · 1.54 KB
/
StandardIterator.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
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Data-Structures-In-Java
* StandardIterator.java
*/
package com.deepak.data.structures.Iterators;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* <br> Problem Statement :
*
* Implement a Standard Iterator for a collection, which
* can loop through elements and consists of all operations
* supported by a iterator
*
* </br>
*
* @author Deepak
*/
public class StandardIterator<T> implements Iterator<T> {
/* This iterator works on list */
private List<T> values;
/* Index to keep track of current access */
private int index;
/**
* Constructor
*
* @param values
*/
public StandardIterator(List<T> values) {
this.values = values;
this.index = 0;
}
/**
* Constructor with Comparator
*
* @param values
* @param comparator
*/
public StandardIterator(List<T> values, Comparator<T> comparator) {
Collections.sort(values, comparator);
this.values = values;
this.index = 0;
}
/**
* Method to check of next element exists
*/
@Override
public boolean hasNext() {
return values.size() != index;
}
/**
* Method to get the next element in collection
*/
@Override
public T next() {
if (hasNext()) {
return values.get(index++);
} else {
throw new NoSuchElementException("No elements left in collection!!");
}
}
/**
* Method to remove element from the collection
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported!!");
}
}