public class LinearSearch {
private LinearSearch(){}
public static <E> int search(E[] data, E target){ //泛型方法
for(int i = 0; i < data.length; i++)
if(data[i].equals(target)) //equals用于值相等,尽量不写==
return i;
return -1;
}
public static void main(String[] args){
Integer[] data = {24, 18, 12, 9, 16, 66, 32, 4}; //手动修改数组类型
int res1 = LinearSearch.search(data, 16); //自动转换泛型类,数组型不能
System.out.println(res1);
int res2 = LinearSearch.search(data, 666);
System.out.println(res2);
//以下代码可不需要-----------------------------
Student[] students = {new Student("Alice"),
new Student("Bob"),
new Student("Charles")};
Student bob = new Student("bOb"); //不区分大小写
int res3 = LinearSearch.search(students, bob);
System.out.println(res3);
}
}