java 不能使用 char 类型的 ArrayList 作为方法的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10483139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:14:55  来源:igfitidea点击:

Cannot use ArrayList of type char as method's argument

javagenerics

提问by J.Olufsen

Cannot define ArrayList<char>as argument of validate. Why it cannot be done? When trying ArrayList<?>it works. Why? Should ArrayList<?>be used instead of ArrayList<char>? What is the difference?

不能定义ArrayList<char>为 的参数validate。为什么做不到?当尝试ArrayList<?>它的工作。为什么?应该ArrayList<?>ArrayList<char>? 有什么区别?

public boolean validate(ArrayList<char> args){ ... }

Error: Syntax error on token "char", Dimensions expected after this token

错误: Syntax error on token "char", Dimensions expected after this token

回答by Bozho

public boolean validate(List<Character> args){ ... }

It has to be the wrapper type - Character- List<Character>. You can't use generics with primitive types.

它必须是包装器类型 - Character- List<Character>。您不能对原始类型使用泛型。

回答by Pau Kiat Wee

public boolean validate(ArrayList<Character> args){ ... }

When use generic in java, you cant use primitive data type, but you can use Character, which is Object that represent primitive charwith little overhead in memory.

在 java 中使用泛型时,不能使用原始数据类型,但可以使用Character,它是代表原始char内存的Object ,内存开销很小。

回答by npinti

You could try to do something like so: public boolean validate(ArrayList<Character> args){ ... }

你可以尝试做这样的事情: public boolean validate(ArrayList<Character> args){ ... }

回答by Makoto

In general, when you'r dealing with a generic object, such as ArrayList<T>, you are required to use objects. The difference between charand Characteris that Characteris an object, and is permitted to be used inside of a generic object.

通常,当您处理通用对象(例如 )时ArrayList<T>,您需要使用对象。char和之间的区别在于CharacterCharacter是一个对象,并且允许在通用对象内部使用。

For reference, each primitive type has their own wrapper object. You can check that out here.

作为参考,每个原始类型都有自己的包装对象。你可以在这里查看

回答by Arianule

The wrapper class of char in Java is Character and char should be specified as Character when adding char objects or validating char objects in an ArrayList.

Java中char的包装类是Character,在ArrayList中添加char对象或验证char对象时,应将char指定为Character。

ArrayList<Character>list = new ArrayList<Character>();