查看: 2520| 回复: 4
跳转到指定楼层
上一主题 下一主题
收起左侧

LinkedList<AnyType> implements Iterable<AnyType> 求解释

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
  1. public class LinkedList<AnyType> implements Iterable<AnyType>
  2. {
  3.    private Node<AnyType> head;
复制代码
在LinkedList中,为什么Node也要使用generic呢?我觉得这样写不就可以了么
  1. private class Node{
  2.         T data;
  3.         Node next;

  4.         public Node(T data){
  5.             this.data = data;
  6.             this.next = null;
  7.         }
  8.     }
复制代码
以及在下面:
  1. /*******************************************************
  2. *
  3. *  The Node class
  4. *
  5. ********************************************************/
  6.    private static class Node<AnyType>
  7.    {
  8.       private AnyType data;
  9.       private Node<AnyType> next;

  10.       public Node(AnyType data, Node<AnyType> next)
  11.       {
  12.          this.data = data;
  13.          this.next = next;
  14.       }
  15.    }

  16. /*******************************************************
  17. *
  18. *  The Iterator class
  19. *
  20. ********************************************************/

  21.    public Iterator<AnyType> iterator()
  22.    {
  23.       return new LinkedListIterator();
  24.    }

  25.    private class LinkedListIterator  implements Iterator<AnyType>
  26.    {
  27.       private Node<AnyType> nextNode;

  28.       public LinkedListIterator()
  29.       {
  30.          nextNode = head;
  31.       }

  32.       public boolean hasNext()
  33.       {
  34.          return nextNode != null;
  35.       }

  36.       public AnyType next()
  37.       {
  38.          if (!hasNext()) throw new NoSuchElementException();
  39.          AnyType res = nextNode.data;
  40.          nextNode = nextNode.next;
  41.          return res;
  42.       }

  43.       public void remove() { throw new UnsupportedOperationException(); }
  44.    }
复制代码
然后在这一段代码中,谁能帮忙解释下为什么迭代器要这样用吗?先申明一个内部类Iterator,但是为什么后面又新建一个LinkedListIterator来回调这个interator呢?


这个好像是叫做回调吧??这里一直没搞懂%>_<%


求解答~~~

上一篇:关于eclipse我有一个问题
下一篇:请教一下大家strStr()的问题
🔗
 楼主| sanguine 2014-10-30 03:11:51 | 只看该作者
全局:
jy02677290 发表于 2014-10-29 12:41
完整的用法应该是这样
http://tutorials.jenkov.com/java-generics/implementing-iterable.html
你要使用 ...

懂了……

然后最上面的问题,为什么Node也需要泛型呢?我觉得直接下面这种写法不就足够了吗?
  1. private class Node{
  2.         T data;
  3.         Node next;

  4.         public Node(T data){
  5.             this.data = data;
  6.             this.next = null;
  7.         }
  8.     }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表