Serious generics issue: int vs. Integer java

☆樱花仙子☆ 提交于 2020-03-05 01:31:35

问题


for a long while, i have been trying to get a piece of code to work, and it just is not possible. the class i have requires a generic which i have set to Integer. so i tried the follwoing:

public class a<T> //set generics for this function
{
    private T A;
    protected boolean d;

    public a(final T A)
    {
        this.A = A;

        //do calculations
        //since constructor cannot return a value, pass to another function.
        this.d = retnData(Integer.parseInt(A.toString()) != 100); //convert to an integer, the backwards way.
    }
    private boolean retnData(boolean test)
    {
        return test;
    }
}
// IN ANOTHER CLASS
transient a<Integer> b;
boolean c = b.d = b.a(25); // throws an erorr: (Int) is not apporpriate for a<Integer>.a

Java will not allow this since java sees that int != Integer, even though both accept the same data. and because of the way generics works i cannot set a b; because of the primitiveness of the type int. Even casting to an Integer does not work, as it still throws the "type error"

finnaly, i have to ask if there is some sort of work around for this, or is it futile to try and get this to work?


回答1:


You are trying to explicitly call a constructor as an instance method. This cannot be done in Java.

Perhaps you want:

transient a<Integer> b = new a<Integer>(25);
boolean c = b.d;

However, since d is declared to be protected, that will only work if this code is in another class derived from a or in the same package.




回答2:


Use

final a<Integer> b = new a<Integer>(10); 
boolean c = b.d;

int can be explicitly converted to Integer with new Integer(10) or Integer.valueOf(10)




回答3:


The code does not make much sense: b is an object of type a, which does not have an a method - so not sure what you expect from b.a(25);... This has nothing to do with int vs Integer...



来源:https://stackoverflow.com/questions/12846624/serious-generics-issue-int-vs-integer-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!