1 | /* This file is part of Aard Dictionary for Android <http://aarddict.org>. |
2 | * |
3 | * This program is free software: you can redistribute it and/or modify |
4 | * it under the terms of the GNU General Public License version 3 |
5 | * as published by the Free Software Foundation. |
6 | * |
7 | * This program is distributed in the hope that it will be useful, |
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
10 | * GNU General Public License <http://www.gnu.org/licenses/gpl-3.0.txt> |
11 | * for more details. |
12 | * |
13 | * Copyright (C) 2010 Igor Tkach |
14 | */ |
15 | |
16 | package aarddict; |
17 | |
18 | import java.util.ArrayList; |
19 | import java.util.Comparator; |
20 | import java.util.HashSet; |
21 | import java.util.Iterator; |
22 | import java.util.List; |
23 | import java.util.Set; |
24 | |
25 | public final class MatchIterator implements Iterator<Entry> { |
26 | |
27 | public static int MAX_FROM_VOL = 50; |
28 | |
29 | Entry next; |
30 | int currentVolCount = 0; |
31 | Set<Entry> seen = new HashSet<Entry>(); |
32 | List<Iterator<Entry>> iterators = new ArrayList<Iterator<Entry>>(); |
33 | |
34 | MatchIterator(Iterable<Volume> dictionaries, Comparator<Entry>[] comparators, LookupWord word) { |
35 | for (Volume vol : dictionaries) { |
36 | for (Comparator<Entry> c : comparators) { |
37 | iterators.add(vol.lookup(word, c)); |
38 | } |
39 | } |
40 | prepareNext(); |
41 | } |
42 | |
43 | |
44 | MatchIterator(Comparator<Entry>[] comparators, Iterable<Volume> dictionaries, LookupWord word) { |
45 | for (Comparator<Entry> c : comparators) { |
46 | for (Volume vol : dictionaries) { |
47 | iterators.add(vol.lookup(word, c)); |
48 | } |
49 | } |
50 | prepareNext(); |
51 | } |
52 | |
53 | private void prepareNext() { |
54 | if (!iterators.isEmpty()) { |
55 | Iterator<Entry> i = iterators.get(0); |
56 | if (i.hasNext() && currentVolCount <= MAX_FROM_VOL) { |
57 | next = i.next(); |
58 | if (!seen.contains(next)) { |
59 | seen.add(next); |
60 | currentVolCount++; |
61 | } |
62 | else { |
63 | next = null; |
64 | prepareNext(); |
65 | } |
66 | } |
67 | else { |
68 | currentVolCount = 0; |
69 | iterators.remove(0); |
70 | prepareNext(); |
71 | } |
72 | } |
73 | else { |
74 | next = null; |
75 | } |
76 | } |
77 | |
78 | public boolean hasNext() { |
79 | return next != null; |
80 | } |
81 | |
82 | public Entry next() { |
83 | Entry current = next; |
84 | prepareNext(); |
85 | return current; |
86 | } |
87 | |
88 | public void remove() { |
89 | throw new UnsupportedOperationException(); |
90 | } |
91 | } |