Java Generics(简单的案例,用于推断的明确谜)

Whi*_*cal 1 java generics constructor types inference

我有这门课,仅仅是为了学习:

public class MyClass{ //Looking for a solution without making my class also generic <Type>  

    //Private Arraylist var to hold the value called myvar 

   public MyClass(ArrayList<MyDesiredType> incoming) {
        //CODE   myVar=incoming  
    }

    public MyDesiredType getType() {
        return myVar.get(0);
    }   
}
Run Code Online (Sandbox Code Playgroud)

是否有任何方法可以在传入对象中从构造函数推断到方法的返回类型而没有警告和转换以及失去类型安全性,但最重要的是没有使整个类GENERIC(对我来说似乎多余)?如果没有,为什么我认为这对编译器不可行?

这是我已经做过的重新提出的问题,但这是我的第一个问题,我学会了如何将其公开,因为没有人理解.我试图稍后编辑原始问题,但一切都被埋没了.我改变并简化了示例,并尝试放轻松.原始问题:Java Generics Silly Thing(为什么我不能推断出这种类型?).

如果有任何问题,请告诉我,我会删除它.

Dar*_*iop 8

不,那里没有.编译器如何知道要返回的类型?在编译期间,将不知道构造函数中的泛型类型的ArrayList.您要么必须使整个类具有通用性,要么采用其他方法.

考虑一下:

public class Test {
    public static void main(String[] args) {
        List<String> arrList = new ArrayList<String>();
        arrList.add("FOO");
        Test test = new Test(arrList);
        String testStr = test.returnWhat();
        System.out.println("testStr");
    }

    private final List myList; //warning

    public <T> Test(List<T> ttype) {
        myList = ttype;
    }

    public <T> T returnWhat() {
        return (T) myList.get(0); //warning
    }
}
Run Code Online (Sandbox Code Playgroud)

这有效,但会在标记的行上给出警告.所以,实际上没有办法实现你所描述的内容而不会使整个类变得通用.因为,如果:

public class Test {


 public static void main(String[] args) {
        List<String> arrList = new ArrayList<String>();
        arrList.add("FOO");
        Test test = new Test(); // now what?
        String testStr = test.returnWhat(0); // no warning...
        JPanel p = test.returnWhat(0); // goes through without warning, real nice...
        test.returnWhat(0); // returns Object

        Test test2 = new Test(arrList);
        test2.addElement(new Object()); // boom, inserted object into list of string.
        String nono = test2.returnWhat(1); // the universe goes down. assign an object to string without warning. even
                                           // though one COULD think the class is generic.
    }

    // private List<T> myList = new ArrayList<T>(); compiler error, T is unknown
    private List myList = new ArrayList();

    public Test() {
        myList.add(new Object());
    }

    public <T> Test(List<T> ttype) {
        myList = ttype;
    }

    public <T> T returnWhat(int index) {
        return (T) myList.get(index);
    }

    public <T> void addElement(T el) {
        myList.add(el);
    }
}
Run Code Online (Sandbox Code Playgroud)

当myList变为通用时,第二个不会编译.在使用默认构造函数的情况下,编译器如何确定<T>的类型?

此外,这可能导致集合中的对象严重问题,这些对象依赖于仅插入某些类型的事实.

这将生成以下异常:

Exception in thread "main" java.lang.ClassCastException:
java.lang.Object cannot be cast to java.lang.String     at
Test.main(Test.java:27)
Run Code Online (Sandbox Code Playgroud)

我设法说服你了吗?

真正的好问题,顺便说一句.我不得不考虑这个问题.