我尝试用随机值填充 ArrayList。 Arraylists 可以包含字符串、整数、 double 或字符。创建随机值工作正常,但我的问题是我无法编写 insertRandom 方法。它应该插入特定的数据类型(如 double、int 等)。我在下面描述了我希望 insertRandom 方法执行的操作。 我收到警告“类型缓冲区中的方法 insert(T) 不适用于参数(int)。 我用谷歌搜索但没有找到/不明白如何将我的值类型转换为 T 对象,或者如何检查(类似于“instanceof”所做的)我的 ArrayList 包含哪些数据类型。我已经阅读过有关人们在构造函数中用作参数的类类型的信息,但我不允许更改构造函数的参数列表。
public class Buffer <T> {
private ArrayList<T> list;
// constructor
public Buffer (int capacity) {
this.list = new ArrayList<T>();
}
// insert items to buffer
public void insert (T item) {
list.add(item);
}
// insert random values
public void insertRandom () {
check if ArrayList is of type String / Integer / Double
if (ArrayList is-of-type-String) {
insert("ThisString");
}
if (ArrayList is-of-type-Double) {
insert(3.4);
}
}
谢谢并致以最诚挚的问候, 帕特里克
最佳答案
作为一个选项,您可以向构造函数提供对象的 Class
并在 insertRandom()
方法中检查该类,如下所示:
public class Buffer <T> {
private final Class<T> type;
private ArrayList<T> list;
// constructor
public Buffer (int capacity, Class<T> type) {
this.list = new ArrayList<T>();
this.type = type;
}
// insert items to buffer
public void insert (T item) {
list.add(item);
}
// insert random values
public void insertRandom () {
// check if ArrayList is of type String / Integer / Double
if (type == String.class) {
insert((T)"ThisString");
}
if (type == Double.class) {
insert((T)Double.valueOf(3.4));
}
}
}
关于java - 如何在泛型类中设置随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55317170/