泛型java的数组搜索

泛型java的数组搜索,java,arrays,search,generics,Java,Arrays,Search,Generics,我试图搜索任何数据类型(Int、Strings、Chars等)的数组,以查看是否存在与您输入的元素匹配的元素。您应该返回匹配元素的索引。有两个类正在使用 我得到的错误是: "Cannot make a static reference to the non-static method find(Object[], Object) from the type ArraySearch" 它的建议是将方法设置为静态,但是这样做会在搜索类中产生错误: "Cannot make a static ref

我试图搜索任何数据类型(Int、Strings、Chars等)的数组,以查看是否存在与您输入的元素匹配的元素。您应该返回匹配元素的索引。有两个类正在使用

我得到的错误是:

"Cannot make a static reference to the non-static method find(Object[], Object) from the type ArraySearch"
它的建议是将方法设置为静态,但是这样做会在搜索类中产生错误:

"Cannot make a static reference to the non-static type E".
搜索类:

public class ArraySearch<E> {
public int find (E[] array, E item) {
      int index = 0;
      for (int i = 0; i < array.length; i++) {
          if (array[i].equals(item)) {
              System.out.println("There is a element " + array[i] + 
                      " at index " + i);
              index = i;
              break;
          }
      }
      return index;
  }
}
public class ArraySearchRunner {

public static void main(String[] args) {

    String[] strings = new String[]{"Jim", "Tim", "Bob", "Greg"};
    Integer[] ints = new Integer[]{1, 2, 3, 4, 5};

    ArraySearch.find(strings, "Bob");
    ArraySearch.find(ints, 4);


}
}
在这种情况下,最好的解决方案是什么


谢谢,

您需要创建类的实例来调用实例方法。大概是这样的:

class Demo {
    public void show() { }
}

new Demo().show();
现在,让您实例化泛型类

此外,您的
find()
方法也被破坏。如果找不到元素,它将返回一个
索引=0
。这是数组中的有效索引。您应该将
索引初始化为
-1

int index = -1;
关于将方法设置为静态的尝试,它会给您带来错误,因为类型参数不适用于类的
static
成员

发件人:

类的类型参数的作用域是该类的整个定义,但该类的任何静态成员或静态初始值设定项除外。这意味着类型参数不能用于静态字段或方法的声明中,也不能用于静态嵌套类型或静态初始值设定项中


是啊,但我写的一切都超越了我自己。只是不确定如何实现上述部分。@chrylis。没关系,OP已经展示了他的尝试。@RohitJain如果这不是家庭作业,我会说使用
contains()
;-)@克丽利斯。当然但是对于数组没有
contains()
方法。但是我明白你在说什么了。
Arrays.asList(a).contains(e)
Gotcha。这是有道理的。谢谢你的帮助。