Java-声明新的通用集时出现意外的类型错误 [英] Java- Getting unexpected type error when declaring new generic set

查看:84
本文介绍了Java-声明新的通用集时出现意外的类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我知道我在使用泛型,但是显然不知道.

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

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

编译后给出:

error: unexpected type
ArraySetList<char> setA = new ArraySetList<char>();
             ^
required: reference
found:    char

以及所有后续字符的相同错误.我想知道如何声明一个新的字符ArraySetList.

As well as the same error for all subsequent char's. I'm wondering how to declare a new ArraySetList of characters.

这是我所有的文件.

http://pastebin.com/4h37Xvu4     // ArraySetList (extends ArrayUnsortedList)
http://pastebin.com/FxmynzkC     // Driver
http://pastebin.com/CgVA0zjY     //ArrayUnsortedList (implements ListInterface)
http://pastebin.com/3iXrCsCc     //ListInterface\

推荐答案

Java泛型适用于对象,而不适用于原始数据类型.但是,如果需要存储原始数据类型,则需要使用其对应的包装器类对象.
这些类只是包装"原始数据类型,使它们具有对象外观.

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.

对于char,相应的包装器类是Character,因此,您必须这样编写代码行:

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>();   

请阅读: http://docs.oracle.com/javase /tutorial/java/data/numberclasses.html

但是,当添加元素时,将添加普通的char.这是因为Java会自动为您将其转换为Character,并在需要时自动将其转换回char .这称为自动装箱转换.

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.

自动装箱是Java编译器进行的自动转换 在原始类型及其对应的对象包装器之间 类.例如,将int转换为Integer,将double转换为a 双重,依此类推.如果转换结果相反,这是 称为拆箱.

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.

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

这篇关于Java-声明新的通用集时出现意外的类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆