[英]Error “Can only iterate over an array or an instance of java.lang.Iterable” using iterator on a class that contains a private collection
i want to use an Iterator on a class that has a collection (defined by me as a dictionary) on which I implemented the Iterator. 我想在具有实现了迭代器的集合(由我定义为字典)的类上使用迭代器。 How can I do?
我能怎么做? Do I have to call back the private field of the class when I have to do a for-each loop?
当我必须进行for-each循环时,是否必须回调该类的私有字段? Here is the code of the collection class:
这是集合类的代码:
public class ArrayDict<K, V> implements Dictionary<K, V> {
Coppia<K, V>[] dict = new Coppia[1];
int n = 0;
@Override
public Iterator<K> iterator() {
return new Iterator<K>() {
private int i = 0;
@Override
public boolean hasNext() {
return i < n;
}
@Override
public K next() {
int pos = i;
i++;
return(K) dict[pos].key;
}
};
}
@Override
public void insert(K key, V value) {
if(search(key)==null)
throw new EccezioneChiavePresente("Chiave già presente");
dict[n] = new Coppia<K,V>(key, value);
n++;
if (n == dict.length) {
Coppia<K,V>[] tmp = new Coppia[dict.length * 2];
for (int i = 0; i < n; i++)
tmp[i] = dict[i];
dict = tmp;
}
}
@Override
public void delete(K key) {
if (n == 0)
throw new EccezioneDizionarioVuoto("Dizionario vuoto");
if (search(key) == null)
throw new EccezioneChiaveNonPresente("Chiave non presente");
int i;
for (i = 0; i < n; i++)
if (dict[i].key.equals(key))
break;
for (int j = i; j < n - 1; j++)
dict[j] = dict[j + 1];
n--;
if (n > 0 && n < dict.length / 4) {
Coppia<K,V>[] tmp = new Coppia[dict.length / 2];
for (i = 0; i < n; i++)
tmp[i] = dict[i];
dict = tmp;
}
}
@Override
public V search(K key) {
if(n==0)
throw new EccezioneDizionarioVuoto("Dizionario vuoto");
for (int i = 0; i < n; i++)
if (dict[i].key.equals(key))
return dict[i].value;
return null;
}
} }
And here is a part of the class that use the collection as private field: 这是使用集合作为私有字段的类的一部分:
public abstract class BibliotecaAbs {
protected Dictionary<String, Record> volumi;
public boolean bibliotecaVuota() {
try {
volumi.delete("");
} catch (EccezioneDizionarioVuoto e) {
return true;
}
return false;
}
public void addVol(String posizione, Volume volume) {
try {
volumi.insert(posizione, new Record(volume, false));
} catch (EccezioneChiavePresente e) {
throw new EccezioneScaffaleOccupato();
}
}
Naturally I have a derived class that makes BibliotecaAbs
concrete. 自然,我有一个派生类使
BibliotecaAbs
具体化。 I want to do something like this: 我想做这样的事情:
for(Object s : b){
String intpos = s.toString();
But it gaves me the error: 但这给了我错误:
Can only iterate over an array or an instance of java.lang.Iterable
只能迭代一个数组或java.lang.Iterable的实例
How can I do to solve this problem? 如何解决这个问题? Any help would be appreciated
任何帮助,将不胜感激
将implements Iterable<SomeType>
添加到BibliotecaAbs
的类声明中,并实现所需的方法public Iterator<SomeType> iterator()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.