gpt4 book ai didi

java - 如何在 Java arraylist 中存储具有泛型类型的数据

转载 作者:行者123 更新时间:2023-11-30 06:52:22 25 4
gpt4 key购买 nike

我会尽力解释我的问题,希望有人能帮助我。

对类:

public class Pair {
String key;
Class<?> value;
public Pair(String key, Class<?> value){
this.key = key;
this.value = value;
};
// you have the setter and getter methods
}

配对类:

public class Pairs {
Pair[] paris = new Pair[0];
// you have the setter and getter methods
public void addPair(Pair pair) {
// assume it will add a pair to the array
}
}

问题:我需要从数据库表中加载数据。这里的列类型不同。有 BOOLEAN、VARCHAR、DATE 等。所以我需要将相应java类型的数据读取并存储到Pair对象中。如何从泛型类型转换为 String 或 Boolean?你如何反过来做?

我找到了将泛型类型转换为字符串的答案:

Class<?> value = getValue();
if (value.isInstance(String.class))
String newValue = (String)(Object) value; // is it correct?

那么我如何将一个字符串转换为类< ?> 并将数据存储到数组列表中呢?因为我想创建:

Pair pair = new Pair("name", value); // but value can be String, Integer, or Boolean

谢谢。

最佳答案

我会首先使 Pair 通用。类似的东西,

public class Pair<T> {
String key;
T value;
public Pair(String key, T value){
this.key = key;
this.value = value;
};
// ...
}

然后为正确的列类型实例化一个 Pair。喜欢,

Pair<String> p = new Pair<>("a", "b");

Pair<Integer> p = new Pair<>("a", 1);

关于java - 如何在 Java arraylist 中存储具有泛型类型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com