类iterator

时间:2016-04-02 10:10:22

标签: java arrays oop linked-list iterator

在练习中,我被要求在java中创建一个string-LinkedList []类型的链接列表数组。为了做到这一点,我创建了一个包装类,其中包含一个名为Bucket的LinkedList属性,并创建了一个桶数组。这是桶类:

import java.util.Iterator;
import java.util.LinkedList;

/**
 * A class representing a bucket in an open hash set of strings.
 * It's a wrapper-class that has a LinkedList<String> that delegates methods to it.
 */
public class Bucket implements Iterable{
    private LinkedList<String> listOfStrings = new LinkedList<>();

    //Methods

    /**
     * @param searchValue a string to check.
     * @return true if the property listOfString contains searchValue false otherwise.
     */
    public boolean contains (String searchValue) {
        return listOfStrings.contains(searchValue);
    }

    /**
     * @param newValue A string to add to the property listOfString.
     * @return true if newValue wasn't in the list and was added successfully, false other wise.
     */
    public boolean add (String newValue){
        if (contains(newValue)){
            return false;
        } else {
            listOfStrings.add(newValue);
            return true;
        }
    }

    /**
     * @param toDelete a string to delete from the property listOfString.
     * @return true if the String was in the property listOfString and was deleted successfully false
     * otherwise.
     */
    public boolean delete (String toDelete){
        if (contains(toDelete)){
            listOfStrings.remove(toDelete);
            return true;
        } else{
            return false;
        }
    }

    @Override
    public Iterator<String> iterator(){
        return listOfStrings.iterator();
    }


}

bucket类委托LinkedList中的方法,这样我就可以将它用作链表的数组。当我尝试迭代它时问题就开始了:

simpleHashArray = new Bucket[newTableSize];//an array of Buckets
for (Bucket bucketToCheck : simpleHashArray){
    for(String stringToAdd : bucketToCheck){
        add(stringToAdd);
    }
}

在第二个中出现错误:不兼容的类型。由于某种原因,它期望类型为Object而不是String类型。

你知道为什么吗?我该怎么办? 谢谢!

1 个答案:

答案 0 :(得分:1)

Iterable是java中的通用接口。这意味着它在类型上进行参数化,并期望特定的类型参数来标识底层集合中的对象类型。如果省略类型参数,只需获取Iterable<Object>

为了能够在您的收藏中使用Strings而不进行明确投射,请将您的Bucket声明更改为:

public class Bucket implements Iterable<String> {
...
}