Java 带有增强for循环的ClassCastException
灵感来源于一个问题,当时我正在摆弄一个实验性的收藏品:Java 带有增强for循环的ClassCastException,java,enums,coding-style,Java,Enums,Coding Style,灵感来源于一个问题,当时我正在摆弄一个实验性的收藏品: /** * 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; privat
/**
* 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));
}
}
是否有什么东西我错过了——也许是咖啡不够
请忽略不正确的size
方法-我确信这不是问题的原因
PS:jdk=jdk1.8.0_11,但使用jdk1.7.0_65仍然失败您实例化了一个原始类型的
样本
,因此样本。在您的情况下,
项的类型将是对象[]
而不是字符串[]
。在test()
方法中:
Samples<String> samples = new Samples(4, "A", "B", "C", "D", "E");
Samples-Samples=新样本(4,“A”、“B”、“C”、“D”、“E”);
将其更改为:
// Note the diamond operator: <>
Samples<String> samples = new Samples<>(4, "A", "B", "C", "D", "E");
//注意菱形运算符:
样本=新样本(4,“A”、“B”、“C”、“D”、“E”);
作为旁注:在
示例
类中,您不需要声明您实现了集合
,因为抽象集合
已经实现了。异常的确切来源是什么?Stacktrace?@icza-在为(字符串[]s:samples){读取的行上。
// Note the diamond operator: <>
Samples<String> samples = new Samples<>(4, "A", "B", "C", "D", "E");