Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 遍历类型T的列表并搜索值_Java_List_Search_Generics_Types - Fatal编程技术网

Java 遍历类型T的列表并搜索值

Java 遍历类型T的列表并搜索值,java,list,search,generics,types,Java,List,Search,Generics,Types,基本上我想写一个函数,它接受类型为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 need

基本上我想写一个函数,它接受类型为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;
}
@SuppressWarnings(“未选中”)
公共静态布尔listContains(列表源、字符串字段、字符串值){
for(T:source){
if(t.get[field]().equals(value))//getField需要是动态的。只有反射方式吗?
返回true;
}
返回false;
}
有什么想法吗


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

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


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

您的方法不是泛型的,因为它应该接受任何类型的对象,所以您可以将列表类型更改为
列表源代码

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; 
}
公共静态布尔listContains(列表源、字符串字段、字符串值){
用于(对象对象对象:源){
试一试{
字段f=obj.getClass().getDeclaredField(字段);//使用名称获取字段
f、 setAccessible(true);
Object val=f.get(obj);//当前对象中字段的值
if(value.equals(val)){//如果它等于传递的值
return true;//返回true
}
}catch(NoSuchFieldException){//如果对象没有字段
return false;//return false
}catch(异常e){//它们是其他异常
抛出新的RuntimeException(e);//您希望如何处理
}
}
返回false;
}

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


publicstaticbooleanlistcontains(List考虑flollwoing示例

        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;
          }
公共类BST
扩展抽象树{
保护树根;
受保护的整数大小=0;
/**创建默认的二叉树*/
公共BST(){
}
/**从对象数组创建二叉树*/
公共BST(E[]对象){
for(int i=0;i0){
current=current.right;
}
else//元素与当前的.element匹配
返回true;//找到元素
}
返回false;
}

反射是您需要研究的内容

尽管使用反射手工制作会奏效,但鉴于您已经提到了
getField
,我强烈建议您研究所有这些bean实用程序

比如说,

您可以执行以下操作:

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

-有什么问题吗?
return PropertyUtils.isReadable(obj, field)
       && value.equals(PropertyUtils.getSimpleProperty(obj, field));