相关疑难解决方法(0)

Java:通配符类型不匹配导致编译错误

我在我的项目中创建了一个工厂类,它允许我(理论上)为任何(支持的)给定类型创建管理器.与管理器交互允许我改变给定类型的某些属性.我面临的问题是当我尝试为泛型类型创建一个管理器时,编译器会破坏我的希望和梦想.

以下代码是我正在使用的精简版本.我尝试创建'test3Manager'的行不会编译,我试图理解为什么会这样.它下面的行显示了一个'解决方法',我试图避免.

    import java.util.List;

    public class GenTest {
        public static void main(String[] args) {
            String test1 = "";
            IRandomType<String> test2 = null;
            IAnotherRandomType<?> test3 = null;

            IManager<String> test1Manager = Factory.createManager(test1);
            IManager<IRandomType<String>> test2Manager = Factory.createManager(test2);
            IManager<IAnotherRandomType<?>> test3Manager = Factory.createManager(test3); // Doesn't compile. Why?

            // Work around?
            IManager<?> test3ManagerTmp = Factory.createManager(test3);
            IManager<IAnotherRandomType<?>> test3Manager2 = (IManager<IAnotherRandomType<?>>) test3ManagerTmp;
        }

        public interface IRandomType<T> {}
        public interface IAnotherRandomType<T> {}
        public interface IManager<T> {}

        public static class Factory {
            public static <T> IManager<T> createManager(T object) {
                return …
Run Code Online (Sandbox Code Playgroud)

java generics wildcard

5
推荐指数
1
解决办法
1005
查看次数

有界通配符相关的编译器错误

我想知道这段代码有什么问题:

Map <? extends String, ? extends Integer> m = null;
Set<Map.Entry<? extends String, ? extends Integer>> s = m.entrySet();
Run Code Online (Sandbox Code Playgroud)

编译器抱怨错误消息:

类型不匹配:无法转换Set<Map.Entry<capture#1-of ? extends String,capture#2-of ? extends Integer>>Set<Map.Entry<? extends String,? extends Integer>>

应该是什么类型的s?Eclipse建议,Set<?>但我想尝试更具体.

java generics bounded-wildcard

3
推荐指数
1
解决办法
1246
查看次数

标签 统计

generics ×2

java ×2

bounded-wildcard ×1

wildcard ×1