【问题标题】:ClassCastException with enhanced for loop具有增强 for 循环的 ClassCastException
【发布时间】:2014-07-29 10:33:17
【问题描述】:

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 失败

【问题讨论】:

  • 异常究竟来自哪里?堆栈跟踪?
  • @icza - 在for (String[] s : samples) {的行上。

标签: java enums coding-style


【解决方案1】:

您实例化了 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 已经实现了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 2014-02-23
    • 2011-01-20
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多