如何实现Iterable [英] How to implements Iterable
本文介绍了如何实现Iterable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要在foreach循环中使用它,LinkedList需要实现Iterable吗?
<$ (节点节点:llist){
System.out.print(node.getData()+); pre>
$ b $ p
$ b $ p $这里是我的LinkedList类。请让我知道如何使它可以迭代?
public class LinkedList implements Iterable {
private Node head = null ;
private int length = 0;
public LinkedList(){
this.head = null;
this.length = 0;
}
LinkedList(节点头){
this.head = head;
this.length = 1;
LinkedList(LinkedList ll){
this.head = ll.getHead();
this.length = ll.getLength();
$ b $ public void appendToTail(int d){
...
}
public void appendToTail(Node node){
...
}
public void deleteOne(int d){
...
}
public void deleteAll (int d){
...
}
public void display(){
...
}
public Node getHead(){
return head;
}
public void setHead(Node head){
this.head = head;
}
public int getLength(){
return length;
}
public void setLength(int length){
this.length = length;
$ b public boolean isEmpty(){
if(this.length == 0)
return true;
返回false;
$ / code $ / pre
解决方案 Iterable
接口的唯一方法 iterator()
。
您将需要返回一个 Iterator
。通常这是通过创建一个实现 Iterator
的内部类,并通过创建该内部类的一个实例来实现 iterator
并返回它。
In my program, I write my own LinkedList class. And an instance, llist.
To use it in foreach loop as following, LinkedList needs to implement Iterable?
for(Node node : llist) {
System.out.print(node.getData() + " ");
}
Here following is my LinkedList class. Please let me know how can I make it Iterable?
public class LinkedList implements Iterable {
private Node head = null;
private int length = 0;
public LinkedList() {
this.head = null;
this.length = 0;
}
LinkedList (Node head) {
this.head = head;
this.length = 1;
}
LinkedList (LinkedList ll) {
this.head = ll.getHead();
this.length = ll.getLength();
}
public void appendToTail(int d) {
...
}
public void appendToTail(Node node) {
...
}
public void deleteOne(int d) {
...
}
public void deleteAll(int d){
...
}
public void display() {
...
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public boolean isEmpty() {
if(this.length == 0)
return true;
return false;
}
}
解决方案 Implement the only method of the Iterable
interface, iterator()
.
You will need to return an instance of Iterator
in this method. Typically this is done by creating an inner class that implements Iterator
, and implementing iterator
by creating an instance of that inner class and returning it.
这篇关于如何实现Iterable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文