简体   繁体   English

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

[英]how to store data with generic types in an Java arraylist

I will try my best to explain my problem and hopefully someone can help me. 我会尽力解释我的问题,希望有人可以帮助我。

Pair class: 配对班:

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
}

Pairs class: 配对类:

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
   }
}

Problem: I need to load data from a database table. 问题:我需要从数据库表中加载数据。 The column types are different here. 此处的列类型不同。 There are BOOLEAN, VARCHAR, DATE and others. 有BOOLEAN,VARCHAR,DATE等。 So I need to read and store the data with corresponding java type into the Pair object. 因此,我需要将具有相应Java类型的数据读取并存储到Pair对象中。 How do you convert from generic type to String or Boolean? 如何从通用类型转换为字符串或布尔值? And how do you do the other way around? 以及您将如何做?

I found an answer for converting generic type to String: 我找到了将泛型转换为String的答案:

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

Then how can I convert a String to Class< ?> and store the data into the arraylist? 那么如何将String转换为Class <?>并将数据存储到arraylist中呢? Because I want to create: 因为我要创建:

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

Thanks. 谢谢。

I would start, by making Pair generic. 首先,使Pair成为通用。 Something like, 就像是,

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

Then you instantiate a Pair for the correct column type. 然后,为正确的列类型实例化一个Pair Like, 喜欢,

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM