Java- Getting unexpected type error when declaring new generic set

前端 未结 2 1864
天命终不由人
天命终不由人 2021-01-02 07:29

I thought I knew what I was doing with generics, but apparently not.

ArraySetList setA = new ArraySetList();

When c

相关标签:
2条回答
  • 2021-01-02 08:00

    Java Generics work for objects and not for primitive data types. If you, however, need to store primitive data types, you will need to use their corresponding wrapper class objects.
    These classes just "wrap" around the primitive data type to give them an object appearance.

    For char, the corresponding wrapper class is Character and hence, you must write your line of code as so:

    ArraySetList<Character> setA = new ArraySetList<Character>();   
    

    Please read: http://docs.oracle.com/javase/tutorial/java/data/numberclasses.html

    When you add elements, however, you will add normal char. That is because Java will automatically convert it into Character for you and back to char automatically, if need be. This is called auto-boxing conversion.

    Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

    source: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

    0 讨论(0)
  • 2021-01-02 08:02

    Generic type arguments require reference types (or wilcards).

    You can't use primitive types (for more see restrictions);

    ArraySetList<Character> setA = new ArraySetList<Character>();
    

    Read JLS 4.5.1 Type Arguments and Wildcards for usable types

    0 讨论(0)
提交回复
热议问题