【问题标题】:Iterating through the list of type T and searching for a value遍历类型 T 的列表并搜索一个值
【发布时间】:2013-06-15 09:05:05
【问题描述】:

基本上,我想编写一个函数,它采用类型 T 的列表并搜索具有给定字段名称的给定值。

@SuppressWarnings("unchecked")
public static boolean listContains( List<T> source, String field, String value ) {
     for ( T t : source ) {
         if ( t.get[field]().equals(value) ) // the getField needs to be dynamic. reflection only way? 
             return true;
     }
     return false;
}

有什么想法吗?

如果字段 (getField) 不存在,那么它应该简单地返回 false。

【问题讨论】:

  • -ve 分?这个问题有什么问题?

标签: java list search generics types


【解决方案1】:

您的方法不是通用的,因为它应该接受任何类型的对象,您可以将列表类型更改为List&lt;?&gt; source

public static boolean listContains(List<?> source, String field, String value) {
    for (Object obj : source ) {
        try {
            Field f = obj.getClass().getDeclaredField(field); //get the field using name
            f.setAccessible(true);
            Object val = f.get(obj); //the value of the field in the current object
            if(value.equals(val)) { //if it equals to passed value
                return true;        //return true
            }
        } catch (NoSuchFieldException e) { //if the object doesn't have the field
            return false;                  //return false
        } catch (Exception e) { //their are other exceptions
            throw new RuntimeException(e); //how ever you want to handle
        }
    }
    return false; 
}

您可以创建一个超类型并按如下方式制作您的方法(以避免使用反射)-

public static boolean listContains(List<? extends MyObject> source, String value) {        
    for (MyObject obj : source ) {
        //...
        //... value.equals(obj.getField())
    }
    //...

但这种方法的问题是它会被限制在某些领域。

【讨论】:

    【解决方案2】:

    您应该能够创建一个通用实体 A 并在该实体中拥有一个 getField 方法。此后,使用 List 确保 getField 可以使用。

    或者,您可以使用反射来检查 getField 方法是否存在。但这会很慢。

    【讨论】:

      【解决方案3】:

      考虑下面的例子。

              public class BST<E extends Comparable<E>> 
                  extends AbstractTree<E> {
                  protected TreeNode<E> root;
                  protected int size = 0;
      
                 /** Create a default binary tree */
                   public BST() {
                  }
      
                 /** Create a binary tree from an array of objects */
                public BST(E[] objects) {
                for (int i = 0; i < objects.length; i++)
                insert(objects[i]);
                }
      
                @Override /** Returns true if the element is in the tree */
                public boolean search(E e) {
                TreeNode<E> current = root; // Start from the root
      
                while (current != null) {
                if (e.compareTo(current.element) < 0) {
                current = current.left;
                }
                else if (e.compareTo(current.element) > 0) {
                current = current.right;
                }
                else // element matches current.element
                return true; // Element is found
                }
      
                return false;
                }
      

      【讨论】:

        【解决方案4】:

        反思是你需要研究的。

        虽然使用反射进行手工制作是可行的,但鉴于您提到了getField,我强烈建议您查看所有这些 bean 实用程序。

        例如,Apache Commons BeanUtils

        你可以这样做:

        return PropertyUtils.isReadable(obj, field)
               && value.equals(PropertyUtils.getSimpleProperty(obj, field));
        

        【讨论】:

          猜你喜欢
          • 2015-06-18
          • 1970-01-01
          • 1970-01-01
          • 2015-08-28
          • 2021-06-02
          • 2014-02-11
          • 1970-01-01
          • 2015-08-26
          • 2014-02-19
          相关资源
          最近更新 更多