你将如何创建一个包含混合布尔值和字符的数组列表? [英] How would you create an array list with mixed booleans and chars?
问题描述
当我谈到使用ArrayList时,我是新的。我知道如何创建一个ArrayList与字符串,我知道如何创建一个与整数。我想知道,如何创建一个ArrayList包含两个类型,例如Doubles和Chars(但没有别的)。
I'm kind of new when it comes to using ArrayList. I know how to create an ArrayList with Strings, I know how to create one with Integers. I'm wondering, how do I create an ArrayList containing two types, such as for instance Doubles and Chars (but nothing else).
这是我有, / p>
This is what I have,
ArrayList<double && char> DCList = new ArrayList<double && char>();
显然它是无效的Java代码,所以我的问题是,如何正确表达? p>
Obviously it's not valid Java code, so my question is, how do I express it correctly?
推荐答案
以下是几个事实:
-
您不能在集合中放置原始值(通用类型只能绑定到引用类型)
You can't put primitive values in a Collection (generic types can only bind to reference types)
char
s和 double
s(或 Characters
code> Doubles 考虑到上述问题),您需要声明该列表包含 Character
和 Double
这是对象
:
If you necessarily need to put both char
s and double
s (or Characters
and Doubles
taking the above point into consideration) you need to declare the list to contain the least common subtype of Character
and Double
which is Object
:
List<Object> charsAndDoubles = new ArrayList<Object>();
这将不允许字符串和整数。
以下是我的解决方法:
class MyDatatype {
....
}
class MyDatatypeCharVariant extends MyDatatype {
char data;
...
}
class MyDatatypeDoubleVariant extends MyDatatype {
double data;
...
}
as:
List<MyDatatype> someList = new ArrayList<MyDatatype>();
这篇关于你将如何创建一个包含混合布尔值和字符的数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!