在线性空间查找
使用泛型
- 不可以是基本数据类型,只能是类对象
boolean , byte , char , short , int , long , float , double
- 每个基本数据类型都有对应的包装类
Boolean , Byte , Character , Short , Integer , Long , Float , Double
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)) {return i;}}return -1;}public static void main(String[] args) {Integer[] data = {24, 18, 12, 9, 16, 66, 32, 4};int index = LinearSearch.search(data, 16);System.out.println(index);int index2 = LinearSearch.search(data, 5);System.out.println(index2);Student[] students = {new Student("Alice"), new Student("Bobo"), new Student("Jack")};int index3 = LinearSearch.search(students, new Student("Bobo"));System.out.println(index3);}}public class Student {private String name;public Student(String name) {this.name = name;}@Overridepublic boolean equals(Object o) {if (this == o) {return true;}if (o == null) {return false;}if (this.getClass() != o.getClass()) {return false;}Student another = (Student) o;return this.name.equals(another.name);}}
