Java - Generics vs Casting Objects

前端 未结 4 1157
野的像风
野的像风 2021-01-03 10:32

I have a class Data

with a generic attribute

private T value;

is there nicer way to do the following?
ie

4条回答
  •  暖寄归人
    2021-01-03 11:19

    The point of generics is NOT to allow a class to use different types at the same time.

    Generics allow you to define/restrict the type used by an instance of an object.

    The idea behind generics is to eliminate the need to cast.

    Using generics with your class should result in something like this:

    Data stringData = new Data();
    String someString = stringData.getValue();
    
    Data longData = new Data();
    Long someLong = longData.getValue();
    
    Data> listData = new Data>();
    List someList = listData.getValue();
    

    You should either use Objects and casting --OR-- use generics to avoid casting.

    You seem to believe that generics allow for heterogeneous typing within the same instance.

    That is not correct.

    If you want a list to contain a mixed bag of types, then generics are not appropriate.


    Also...

    To create a long from a double, use Double.longValue().

    To create a float from a double, use Double.floatValue().

    I recommend reading the documentation.

提交回复
热议问题