iterator()方法自动调用

时间:2019-08-12 16:53:26

标签: java collections

我不是Collection Java的新手,如果问题如此基本,请抱歉。

在调试Shipment类中的一段代码时。如果iterator()中的返回值是null,则测试用例失败,但是如果返回值是products.iterator,则测试用例通过。因此,我认为在ShipmentTest类中运行hasItem()时会自动调用iterator()方法。但是奇怪的是,它被调用时没有从测试文件中调用,就像普通代码一样

Iterator itr = al.iterator();

      while(itr.hasNext()) {
         Object element = itr.next();
         // do something....
      }

并且返回类型hasItem()不返回与迭代器相关的值...

任何人都经历过这种情况,可以帮助您分享想法吗?

以下是代码:

ShipmentTest类

import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsCollectionContaining.hasItem;

public class ShipmentTest {

    private Shipment shipment = new Shipment();
    Product door = new Product("Door", 22);
    Product windows = new Product("Windows", 10);

    @Test
    public void shouldAddItems() throws Exception {
        shipment.add(door);
        shipment.add(windows);

        assertThat(shipment, hasItem(door));
    }
}

货运舱

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Shipment implements Iterable<Product> {

    private static final int LIGHT_VAN_MAX_WEIGHT = 20;
    private List<Product> products = new ArrayList<>();

    @Override
    public Iterator<Product> iterator() {
        return products.iterator();
    }

    public void add(Product p) {
        products.add(p);
    }
}

产品类别

public class Product {

    private final String name;
    private final int weight;

    public Product(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public int getWeight() {
        return weight;
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", weight=" + weight +
                '}';
    }
}

1 个答案:

答案 0 :(得分:3)

是的,为了测试集合是否包含某项,IsCollectionContaining.hasItem调用iterator()。这是处理任何Iterable的完全正常的部分。 (还能如何判断货件中是否包含特定物品?)