在线性空间查找

image.png

使用泛型

  • 不可以是基本数据类型,只能是类对象

boolean , byte , char , short , int , long , float , double

  • 每个基本数据类型都有对应的包装类

Boolean , Byte , Character , Short , Integer , Long , Float , Double

  1. public class LinearSearch {
  2. private LinearSearch() {
  3. }
  4. public static <E> int search(E[] data, E target) {
  5. for (int i = 0; i < data.length; i++) {
  6. if (data[i].equals(target)) {
  7. return i;
  8. }
  9. }
  10. return -1;
  11. }
  12. public static void main(String[] args) {
  13. Integer[] data = {24, 18, 12, 9, 16, 66, 32, 4};
  14. int index = LinearSearch.search(data, 16);
  15. System.out.println(index);
  16. int index2 = LinearSearch.search(data, 5);
  17. System.out.println(index2);
  18. Student[] students = {new Student("Alice"), new Student("Bobo"), new Student("Jack")};
  19. int index3 = LinearSearch.search(students, new Student("Bobo"));
  20. System.out.println(index3);
  21. }
  22. }
  23. public class Student {
  24. private String name;
  25. public Student(String name) {
  26. this.name = name;
  27. }
  28. @Override
  29. public boolean equals(Object o) {
  30. if (this == o) {
  31. return true;
  32. }
  33. if (o == null) {
  34. return false;
  35. }
  36. if (this.getClass() != o.getClass()) {
  37. return false;
  38. }
  39. Student another = (Student) o;
  40. return this.name.equals(another.name);
  41. }
  42. }