java - 具有增强 for 循环的 ClassCastException

标签 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));
    }
}

并且发现,如果我拉出一个迭代器并运行,一切正常,但如果我尝试使用增强的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 仍然失败

最佳答案

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

关于java - 具有增强 for 循环的 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25013237/

相关文章:

c++ - 如何将枚举返回值转换为 C++ 异常?

php - PSR-1 2.3 副作用规则

objective-c - 什么时候应该在 Objective-C 方法名称中使用 "and"?

java - AlarmManager 对闹钟应用程序电池的影响

java - Android - 设置同步适配器时启用自动同步

java - Mybatis 枚举通过 id 选择

c# - 使用资源和用户定义的控件属性

java - 正则表达式未正确匹配限制值

java - 如何在 Activiti 进程中从网关调用 Java 方法

c# - 如何在 Enum 上使用多个描述属性