具有增强的for循环的ClassCastException

时间:2014-07-29 10:33:18

标签: java enums coding-style

受到here问题的启发,我正在搞一个实验性的收集:

/**
 * Pretends to be a Collection of samples from the items.
 *
 * @param <T>
 */
class Samples<T> extends AbstractCollection<T[]> implements Collection<T[]> {

    private final int of;
    private final T[] items;

    public Samples(int of, T... items) {
        this.of = of;
        this.items = items;
    }

    @Override
    public int size() {
        // I know this is wrong.
        return items.length * of;
    }

    @Override
    public Iterator<T[]> iterator() {
        // Make the iterator on the fly.
        return new Iterator<T[]>() {
            // Start at the beginning.
            int which = 0;

            @Override
            public boolean hasNext() {
                // That's how many there are.
                return which < size();
            }

            @Override
            public T[] next() {
                // Make my new one by cloning the original.
                T[] next = Arrays.copyOf(items, of);
                // Pick the items with reference to which.
                int count = which;
                for (int i = 0; i < of; i++) {
                    // count mod length is the next one to use.
                    next[i] = items[count % items.length];
                    // Used that now.
                    count /= items.length;
                }
                // Consumed that one.
                which += 1;
                return next;
            }

        };

    }

}

public void test() {
    Samples<String> samples = new Samples(4, "A", "B", "C", "D", "E");
    // Walk it with an iterator.
    Iterator<String[]> i = samples.iterator();
    while (i.hasNext()) {
        System.out.println(Arrays.toString(i.next()));
    }
    // Walk it using enhanced for loop.
    for (String[] s : samples) { // Line 91 - error thrown here.
        System.out.println(Arrays.toString(s));
    }
}

并且发现如果我拉出iterator并且走路一切正常但是如果我尝试使用增强的for循环则会出错:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

有什么我想念的东西 - 咖啡可能不够吗?

请忽略不正确的size方法 - 我确信这不是问题的原因。

PS:jdk = jdk1.8.0_11但jdk1.7.0_65仍然失败

1 个答案:

答案 0 :(得分:3)

您实例化原始类型Samples,因此Samples.items类型为Object[],而不是String[]。在test()方法中:

Samples<String> samples = new Samples(4, "A", "B", "C", "D", "E");

将其更改为:

// Note the diamond operator: <>
Samples<String> samples = new Samples<>(4, "A", "B", "C", "D", "E");

作为旁注:在Samples课程中,您不需要声明实施Collection,因为AbstractCollection已经这样做了。