简体   繁体   中英

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. So I need to read and store the data with corresponding java type into the Pair object. 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:

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? 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. 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. Like,

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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