CS61B - Iterator

本文详细探讨了Java中的Iterator接口及其在ArrayList中的应用。通过创建自定义ArrayList并实现Iterable接口,逐步解析如何使用Iterator遍历列表并打印元素。文章通过控制变量的方法解释了hasNext()和next()方法的作用,并展示了如何在自定义数据结构中实现相同功能。
摘要由CSDN通过智能技术生成

CS61B - Iterator

(码字不易,感觉有点用的话可以点个赞嘛~)

Iterator是什么?

看了CS61B这部分的网课两遍,感觉要好好记录下来,不然接下来还是容易忘。
首先,究竟是什么原因让我们揪出来了Iterator这个东西呢?我们先看一段代码:

//assume we have an ArrayList called AList, which contains String type items
//we want to create a method to print out all the items in the list
public void printAList(ArrayList<String> ALits) {
   
	for(String x : AList) {
   
		System.out.println(x);
	}
 }

这个方法可以打印出AList中的每个元素,运行结果如图所示:
在这里插入图片描述

我们自己创建一个ArrayList!

我们不调用java.util.ArrayList, 而是自己创建一个ArrayList,正好可以借用之前的AList(CS61B之前的课上跟着做的)来用一用这个方法:

public class AList<item> {
   
    private item[] items;
    private int size;

    /** Creates an empty list. */
    public AList() {
   
        items = (item[]) new Object[100];   //create a array which length is 100 (0-99)
        size = 0;
    }

    /** Inserts X into the back of the list. */
    /*
    when you want to add a new value in this list, you'll find that
    it go into position size!
    e.i. [0,0,0,0,0,0,0,0]
   index: 0 1 2 3 4 5 6 7
   if you want to add value, for example, add a[0] = 5
   it happens to be the items[size].
    */

    /** resizes the underlying array to the target capacity */
    private void resize(int capacity){
   
        /**if we type -> item[] a = new item[capacity];
         * error! type item cannot instantiated!
         * Java cannot instantiated generic(通用) type
         * */
        item[] a = (item[]) new Object[capacity];
        System.arraycopy(items, 0, a, 0, size);
        items = a;
    }

    public void addLast(item x) {
   
        /** add items when the array is full (size == items.length)
         */
        if(size == items.length){
   
            resize(size * 2);       //uses multiply to set size, to save time consuming
        }
        items[size] = x;
        size += 1;
    }
    /**we define usage ratio R = size/items.length
     * if R < 0.25, we have to half array size
     * i.e. we use an array, which length i
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值