java unexpected type_Java- Getting unexpected type error when declaring new generic set

问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值