错误“只能在包含私有集合的类上使用迭代器迭代数组或java.lang.Iterable实例”

时间:2016-03-31 16:05:22

标签: java eclipse dictionary iterator iterable

我想在一个具有集合(由我定义为字典)的类上使用Iterator,我在其上实现了Iterator。我能怎么做?当我必须执行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

的实例

如何解决此问题?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

implements Iterable<SomeType>添加到BibliotecaAbs的类声明中,并实现所需的方法public Iterator<SomeType> iterator()