这个e==this什么时候会成立呢????

public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

2个回答

如果自己也在那个 iterator里面,那么this就会等于e

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

public class Test20190327 {

    public static void main(String[] args) {
        Whatever whatever1 = new Whatever();
        Whatever whatever2 = new Whatever();
        Whatever whatever3 = new Whatever();
        Whatever whatever4 = new Whatever();

        whatever3.addToList(whatever1);
        whatever3.addToList(whatever2);
        // 把自己加进这个list里面
        whatever3.addToList(whatever3);
        whatever3.addToList(whatever4);

        System.out.println(whatever3.toString());
    }
}

class Whatever<T> {

    private List<T> list = new ArrayList<T>();
    public void addToList(T t) {
        list.add(t);
    }
    public Iterator<T> iterator() {
        return list.iterator();
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Iterator<T> it = iterator();
        while(it.hasNext()) {
            T t = it.next();
            if (t == this) {
                sb.append("[it's me]");
            } else {
                sb.append("[not me]");
            }
        }
        return sb.toString();
    }
}

结果

[not me][not me][it's me][not me]

这个要看iterator迭代器内部怎么实现的了。它什么情况下会让这个对象本身和迭代器下一个元素相等

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!