Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我怎样才能使我的类具有可移植性,从而可以使用foreach语法?_Java_Foreach_Iterable - Fatal编程技术网

Java 我怎样才能使我的类具有可移植性,从而可以使用foreach语法?

Java 我怎样才能使我的类具有可移植性,从而可以使用foreach语法?,java,foreach,iterable,Java,Foreach,Iterable,我有Book和BookList课程图书列表是这样的: public class BookList { private final List<Book> bList = new ArrayList<Book>(); public int size() { return bList.size(); } public boolean isEmpty() { ... } public boolean contains(Book b) {

我有
Book
BookList
课程<代码>图书列表是这样的:

public class BookList 
{
    private final List<Book> bList = new ArrayList<Book>();

    public int size() { return bList.size(); }

    public boolean isEmpty() {  ... }

    public boolean contains(Book b) { ...  }

    public boolean add(Book b) { ...  }

    public boolean remove(Book b) {  .. } 

    public void clear() { ... }

    public Book get(int index) { ... }
 
}
public class BookList implements Iterable<Book> {
    private final List<Book> bList = new ArrayList<Book>();

    @Override
    public Iterator<Book> iterator() {
        return bList.iterator();
    }

    ...
}
public class BookList implements Iterable<Book> {
    private final List<Book> bList = new ArrayList<Book>();
    //...
    @Override
    public Iterator<Book> iterator() {
        return new Iterator<Book> () {
            private final Iterator<Book> iter = bList.iterator();

            @Override
            public boolean hasNext() {
                return iter.hasNext();
            }

            @Override
            public Book next() {
                return iter.next();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("no changes allowed");
            }
        };
    }
}
Eclipse说:

只能迭代java.lang.Iterable的数组或实例

我如何才能让它工作?

您需要实现接口,这意味着您需要实现
iterator()
方法。在您的情况下,这可能看起来像这样:

public class BookList 
{
    private final List<Book> bList = new ArrayList<Book>();

    public int size() { return bList.size(); }

    public boolean isEmpty() {  ... }

    public boolean contains(Book b) { ...  }

    public boolean add(Book b) { ...  }

    public boolean remove(Book b) {  .. } 

    public void clear() { ... }

    public Book get(int index) { ... }
 
}
public class BookList implements Iterable<Book> {
    private final List<Book> bList = new ArrayList<Book>();

    @Override
    public Iterator<Book> iterator() {
        return bList.iterator();
    }

    ...
}
public class BookList implements Iterable<Book> {
    private final List<Book> bList = new ArrayList<Book>();
    //...
    @Override
    public Iterator<Book> iterator() {
        return new Iterator<Book> () {
            private final Iterator<Book> iter = bList.iterator();

            @Override
            public boolean hasNext() {
                return iter.hasNext();
            }

            @Override
            public Book next() {
                return iter.next();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("no changes allowed");
            }
        };
    }
}
public类BookList实现了Iterable{
私有最终列表bList=newarraylist();
@凌驾
公共迭代器迭代器(){
返回bList.iterator();
}
...
}

要更具体地说明如何“实现
Iterable
接口”:

public类BookList实现了Iterable
{
私有最终列表bList=newarraylist();
... 
@凌驾
公共迭代器迭代器()
{
返回bList.iterator();
}
}
实现接口。这意味着您需要实现一个方法,该方法返回一个对象,该对象将遍历
图书列表的元素

在本例中,您的
iterator()
方法可以只返回调用
bList.iterator()的结果。(这将导致(
for(Book b:somBookList)
BookList.bList
中的
Book
对象上迭代)

在其他情况下,您可能需要编写自己的
迭代器
实现类,包括
T next()
boolean hasNext()
remove()
方法。例如,如果您想防止外部代码通过迭代器从
图书列表中删除元素,可以这样实现:

public class BookList 
{
    private final List<Book> bList = new ArrayList<Book>();

    public int size() { return bList.size(); }

    public boolean isEmpty() {  ... }

    public boolean contains(Book b) { ...  }

    public boolean add(Book b) { ...  }

    public boolean remove(Book b) {  .. } 

    public void clear() { ... }

    public Book get(int index) { ... }
 
}
public class BookList implements Iterable<Book> {
    private final List<Book> bList = new ArrayList<Book>();

    @Override
    public Iterator<Book> iterator() {
        return bList.iterator();
    }

    ...
}
public class BookList implements Iterable<Book> {
    private final List<Book> bList = new ArrayList<Book>();
    //...
    @Override
    public Iterator<Book> iterator() {
        return new Iterator<Book> () {
            private final Iterator<Book> iter = bList.iterator();

            @Override
            public boolean hasNext() {
                return iter.hasNext();
            }

            @Override
            public Book next() {
                return iter.next();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("no changes allowed");
            }
        };
    }
}
public类BookList实现了Iterable{
私有最终列表bList=newarraylist();
//...
@凌驾
公共迭代器迭代器(){
返回新的迭代器(){
私有最终迭代器iter=bList.Iterator();
@凌驾
公共布尔hasNext(){
返回iter.hasNext();
}
@凌驾
公共图书目录下一页(){
返回iter.next();
}
@凌驾
公共空间删除(){
抛出新的UnsupportedOperationException(“不允许更改”);
}
};
}
}

要使类可迭代,您需要实现
Iterable
接口

a) 声明类如下

public class BookList implements Iterable<Book>
public类BookList实现了Iterable
b) 重写
迭代器()
方法


希望它能对您有所帮助。

在这里,我们可以看到使用迭代器和foreach语法的LinkedList的简单实现

class LinkedList implements Iterable<LinkedList.Node>{
    private Node node;
    public void add(Object data){
        if(!Optional.ofNullable(node).isPresent()){
            node = new Node();
            node.setData(data);
        }else{
            Node node = new Node();
            node.setData(data);
            Node lastNode = getLastNode(this.node);
            lastNode.setNext(node);
        }
    }

    private Node getLastNode(Node node){
        if(node.getNext()==null){
            return node;
        }else{
            return getLastNode(node.getNext());
        }
    } 

    class Node{
        private Object data;
        private Node next;
        public Object getData() {
            return data;
        }
        public void setData(Object data) {
            this.data = data;
        }
        public Node getNext() {
            return next;
        }
        public void setNext(Node next) {
            this.next = next;
        }
    }

    public Iterator<Node> iterator() {
        return new NodeIterator();
    }

    class NodeIterator implements Iterator<Node>{
        private Node current;

        public boolean hasNext() {
            if(current == null){
                current = node;
                return Optional.ofNullable(current).isPresent();
            }else{
                current = current.next;
                return Optional.ofNullable(current).isPresent();
            }
        }

        public Node next() {
            return current;
        }
    }
}

public class LinkedListImpl {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.add("data1");
        linkedList.add("data2");
        linkedList.add("data3");
        for(LinkedList.Node node: linkedList){
            System.out.println(node.getData());
        }
    }
}
类LinkedList实现Iterable{
专用节点;
公共void添加(对象数据){
if(!可选.ofNullable(node).isPresent()){
node=新节点();
node.setData(数据);
}否则{
节点=新节点();
node.setData(数据);
Node lastNode=getLastNode(this.Node);
setNext(节点);
}
}
私有节点getLastNode(节点节点){
if(node.getNext()==null){
返回节点;
}否则{
返回getLastNode(node.getNext());
}
} 
类节点{
私有对象数据;
私有节点下一步;
公共对象getData(){
返回数据;
}
公共void setData(对象数据){
这个数据=数据;
}
公共节点getNext(){
下一步返回;
}
公共void setNext(节点next){
this.next=next;
}
}
公共迭代器迭代器(){
返回新节点运算符();
}
类NodeIterator实现迭代器{
专用节点电流;
公共布尔hasNext(){
如果(当前==null){
电流=节点;
返回可选的.ofNullable(当前).isPresent();
}否则{
当前=当前。下一步;
返回可选的.ofNullable(当前).isPresent();
}
}
公共节点下一步(){
回流;
}
}
}
公共类LinkedListImpl{
公共静态void main(字符串[]args){
LinkedList LinkedList=新建LinkedList();
linkedList.add(“数据1”);
linkedList.add(“数据2”);
linkedList.add(“数据3”);
用于(LinkedList.Node节点:LinkedList){
System.out.println(node.getData());
}
}
}

您需要实现该接口。尝试实现
Iterable
接口。您的类在简单列表中添加了什么?它甚至删除了类型安全性,因为它有一个
add(Object)
方法,而不是
add(Book)
。我在真实的应用程序中将对象更改为Book,这是自动生成的eclipse代码,似乎我在发布问题之前忘记了将对象更改为Book。请注意,这将允许调用方在不查看图书列表的情况下删除图书。remove()方法,它破坏了封装。您最好使用
返回Collections.unmodifiableList(bList.iterator()┼“其他情况”部分为1。