![](/img/trans.png)
[英]i am using Collection Can only iterate over an array or an instance of java.lang.Iterable
[英]Error “Can only iterate over an array or an instance of java.lang.Iterable” using iterator on a class that contains a private collection
我想在具有實現了迭代器的集合(由我定義為字典)的類上使用迭代器。 我能怎么做? 當我必須進行for-each循環時,是否必須回調該類的私有字段? 這是集合類的代碼:
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;
}
}
這是使用集合作為私有字段的類的一部分:
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();
}
}
自然,我有一個派生類使BibliotecaAbs
具體化。 我想做這樣的事情:
for(Object s : b){
String intpos = s.toString();
但這給了我錯誤:
只能迭代一個數組或java.lang.Iterable的實例
如何解決這個問題? 任何幫助,將不勝感激
將implements Iterable<SomeType>
添加到BibliotecaAbs
的類聲明中,並實現所需的方法public Iterator<SomeType> iterator()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.