Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 不兼容类型:SomeX无法转换为CAP#1_Java_Generics - Fatal编程技术网

Java 不兼容类型:SomeX无法转换为CAP#1

Java 不兼容类型:SomeX无法转换为CAP#1,java,generics,Java,Generics,我不明白这里出了什么问题 import java.util.*; class Main { private static class SomeX {} void doSomethingWithX(SomeX someX) { Collection<? extends SomeX> colectionOfX = new ArrayList<>(); colectionOfX.add(someX); } } 据我所

我不明白这里出了什么问题

import java.util.*;

class Main {
    private static class SomeX {}

    void doSomethingWithX(SomeX someX) {
        Collection<? extends SomeX> colectionOfX = new ArrayList<>();
        colectionOfX.add(someX);
    }
}
据我所知,
将第1章的下限扩展到
SomeX
,并且
SomeX
本身应满足该限制


怎么了?(使用
javac1.8.0_102
编译)

如果要允许
collectionofx
包含
SomeX
的任何实例,应声明为:

Collection<SomeX> colectionOfX = new ArrayList<>();
collectionofx=newarraylist();
当你宣布它为

Collection<? extends SomeX> colectionOfX = ...;

Collection所以,这个问题实际上已经在“”中得到了回答,但谷歌搜索并没有带来匹配

就我所知,简短的回答如下:

class Main {
    private static class SomeX {}

    private static class SomeY extends SomeX {}

    void doSomethingWithX(SomeX someX) {
        Collection<? extends SomeX> colectionOfX = new ArrayList<SomeY>();
        colectionOfX.add(someX);
    }
}
主类{
私有静态类SomeX{}
私有静态类SomeY扩展了SomeX{}
void doSomethingWithX(SomeX SomeX){

集合所以……所有这些都不能回答“为什么我不能将SomeX的
实例添加到
Collection@XtraCoder正如我试图解释的,
Collection
class Main {
    private static class SomeX {}

    private static class SomeY extends SomeX {}

    void doSomethingWithX(SomeX someX) {
        Collection<? extends SomeX> colectionOfX = new ArrayList<SomeY>();
        colectionOfX.add(someX);
    }
}