aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/result/HitIterator.java
blob: f36a5d77d4006c3f72b84e0a3a2edf242cf9656d (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.result;

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import com.yahoo.search.Result;


/**
 * An iterator for the list of hits in a result. This iterator supports the remove operation.
 *
 * @author Steinar Knutsen
 */
public class HitIterator implements Iterator<Hit> {

    /** The index into the list of hits */
    private int index = -1;

    /** The list of hits to iterate over */
    private List<Hit> hits;

    /** The result the hits belong to */
    private HitGroup hitGroup;

    /** Whether the iterator is in a state where remove is OK */
    private boolean canRemove = false;

    public HitIterator(HitGroup hitGroup, List<Hit> hits) {
        this.hitGroup = hitGroup;
        this.hits = hits;
    }

    public HitIterator(Result result, List<Hit> hits) {
        this.hitGroup = result.hits();
        this.hits = hits;
    }

    public boolean hasNext() {
        if (hits.size() > (index + 1)) {
            return true;
        } else {
            return false;
        }
    }

    public Hit next() throws NoSuchElementException {
        if (hits.size() <= (index + 1)) {
            throw new NoSuchElementException();
        } else {
            canRemove = true;
            return hits.get(++index);
        }
    }

    public void remove() throws IllegalStateException {
        if (!canRemove) {
            throw new IllegalStateException();
        }
        hitGroup.remove(index);
        index--;
        canRemove = false;
    }

}