How to find object of given type in a heterogeneous List

前端 未结 2 1857
既然无缘
既然无缘 2020-12-30 17:32

I have a heterogeneous List that can contain any arbitrary type of object. I have a need to find an element of the List that is of a certain type. Looking through the answer

相关标签:
2条回答
  • 2020-12-30 17:42

    You can define the method using [Class.isInstance()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#isInstance(java.lang.Object)) and [Class.cast()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#cast(java.lang.Object)) method. Here is a sample implementation (with extra argument for the list):

    static <T> T findInList(List<?> list, Class<T> clazz) {
      for (Object o : list) {
        if (clazz.isInstance(o)) {
          return clazz.cast(o);
        }
      }
      return null;
    }
    

    Update: I would recommend against putting multiple types in the Collection. It's usually a sign that either need a custom datatype (e.g. Transaction) or a Tuple value.

    0 讨论(0)
  • 2020-12-30 17:47

    You can use Typesafe Heterogeneous Container pattern described by Josh Bloch. Here is an example from Josh's presentation:

    class Favorites {
        private Map<Class<?>, Object> favorites =
                new HashMap<Class<?>, Object>();
    
        public <T> void setFavorite(Class<T> klass, T thing) {
            favorites.put(klass, thing);
        }
    
        public <T> T getFavorite(Class<T> klass) {
            return klass.cast(favorites.get(klass));
        }
    
        public static void main(String[] args) {
            Favorites f = new Favorites();
            f.setFavorite(String.class, "Java");
            f.setFavorite(Integer.class, 0xcafebabe);
            String s = f.getFavorite(String.class);
            int i = f.getFavorite(Integer.class);
        }
    }
    

    You can easily extend this to support List of favorites per type instead of a single value.

    0 讨论(0)
提交回复
热议问题