Van
Van

Reputation: 189

Java- Getting unexpected type error when declaring new generic set

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

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

When compiled gives:

error: unexpected type
ArraySetList<char> setA = new ArraySetList<char>();
             ^
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\

Upvotes: 13

Views: 24262

Answers (2)

Reimeus
Reimeus

Reputation: 159844

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

Upvotes: 8

An SO User
An SO User

Reputation: 25028

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

Upvotes: 21

Related Questions