问题
I thought I knew what I was doing with generics, but apparently not.
ArraySetList setA = new ArraySetList();
When compiled gives:
error: unexpected type
ArraySetList setA = new ArraySetList();
^
required: reference
found: char
As well as the same error for all subsequent char's. I'm wondering how to declare a new ArraySetList of characters.
Here are all my files.
http://pastebin.com/4h37Xvu4 // ArraySetList (extends ArrayUnsortedList)
http://pastebin.com/FxmynzkC // Driver
http://pastebin.com/CgVA0zjY //ArrayUnsortedList (implements ListInterface)
http://pastebin.com/3iXrCsCc //ListInterface\
回答1:
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 setA = new ArraySetList();
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
回答2:
Generic type arguments require reference types (or wilcards).
You can't use primitive types (for more see restrictions);
ArraySetList setA = new ArraySetList();
Read JLS 4.5.1 Type Arguments and Wildcards for usable types
来源:https://stackoverflow.com/questions/19530816/java-getting-unexpected-type-error-when-declaring-new-generic-set