Java数组查找案例如何编写

wen java案例 28

本文目录导读:

Java数组查找案例如何编写

  1. 线性查找(顺序查找)
  2. 二分查找(适用于已排序数组)
  3. 对象数组查找
  4. 使用Java内置方法查找
  5. 查找并返回多个结果
  6. 最佳实践建议

我来为您介绍Java数组查找的几种常见案例和实现方法。

线性查找(顺序查找)

最简单的查找方法,适用于未排序的数组。

public class LinearSearch {
    public static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;  // 返回目标元素的索引
            }
        }
        return -1;  // 没有找到返回-1
    }
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9, 3};
        int target = 8;
        int index = linearSearch(numbers, target);
        if (index != -1) {
            System.out.println("元素 " + target + " 在索引 " + index + " 处找到");
        } else {
            System.out.println("元素 " + target + " 未找到");
        }
    }
}

二分查找(适用于已排序数组)

效率更高的查找方法,但要求数组必须有序。

public class BinarySearch {
    // 迭代方式实现
    public static int binarySearchIterative(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;  // 防止溢出
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
    // 递归方式实现
    public static int binarySearchRecursive(int[] arr, int target, int left, int right) {
        if (left > right) {
            return -1;  // 基准情况:未找到
        }
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            return binarySearchRecursive(arr, target, mid + 1, right);
        } else {
            return binarySearchRecursive(arr, target, left, mid - 1);
        }
    }
    public static void main(String[] args) {
        int[] sortedNumbers = {1, 3, 5, 7, 9, 11, 13, 15};
        int target = 9;
        // 使用迭代版本
        int index1 = binarySearchIterative(sortedNumbers, target);
        System.out.println("迭代二分查找: " + 
            (index1 != -1 ? "找到于索引 " + index1 : "未找到"));
        // 使用递归版本
        int index2 = binarySearchRecursive(sortedNumbers, target, 0, sortedNumbers.length - 1);
        System.out.println("递归二分查找: " + 
            (index2 != -1 ? "找到于索引 " + index2 : "未找到"));
    }
}

对象数组查找

查找自定义对象数组中的元素。

import java.util.Arrays;
import java.util.Comparator;
class Student {
    private int id;
    private String name;
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() { return id; }
    public String getName() { return name; }
    @Override
    public String toString() {
        return "Student{id=" + id + ", name='" + name + "'}";
    }
}
public class ObjectArraySearch {
    // 按ID查找
    public static Student findById(Student[] students, int targetId) {
        for (Student student : students) {
            if (student.getId() == targetId) {
                return student;
            }
        }
        return null;
    }
    // 按姓名查找
    public static Student findByName(Student[] students, String targetName) {
        for (Student student : students) {
            if (student.getName().equals(targetName)) {
                return student;
            }
        }
        return null;
    }
    // 使用ArrayList查找
    public static Student findUsingList(List<Student> list, int targetId) {
        for (Student s : list) {
            if (s.getId() == targetId) {
                return s;
            }
        }
        return null;
    }
    public static void main(String[] args) {
        Student[] students = {
            new Student(1001, "张三"),
            new Student(1002, "李四"),
            new Student(1003, "王五")
        };
        // 按ID查找
        Student found1 = findById(students, 1002);
        System.out.println("按ID查找结果: " + (found1 != null ? found1 : "未找到"));
        // 按姓名查找
        Student found2 = findByName(students, "王五");
        System.out.println("按姓名查找结果: " + (found2 != null ? found2 : "未找到"));
    }
}

使用Java内置方法查找

利用Java提供的工具类进行查找。

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class BuiltInSearch {
    public static void main(String[] args) {
        // 1. Arrays.binarySearch() - 二分查找
        int[] numbers = {2, 4, 6, 8, 10, 12};
        int index = Arrays.binarySearch(numbers, 8);
        System.out.println("Arrays.binarySearch: " + index);
        // 2. List.contains() - 检查是否存在
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        boolean exists = names.contains("Bob");
        System.out.println("List contains 'Bob': " + exists);
        // 3. List.indexOf() - 获取第一个匹配的索引
        int position = names.indexOf("Charlie");
        System.out.println("'Charlie'在List中的位置: " + position);
        // 4. 使用流(Stream)进行查找
        int[] scores = {85, 92, 78, 95, 88};
        boolean hasScoreAbove90 = Arrays.stream(scores)
                                       .anyMatch(score -> score > 90);
        System.out.println("是否有分数超过90: " + hasScoreAbove90);
        // 查找第一个符合条件的元素
        int firstHighScore = Arrays.stream(scores)
                                  .filter(score -> score > 90)
                                  .findFirst()
                                  .orElse(-1);
        System.out.println("第一个超过90的分数: " + firstHighScore);
    }
}

查找并返回多个结果

当数组中有多个匹配的元素时。

import java.util.ArrayList;
import java.util.List;
public class MultipleResultSearch {
    // 查找所有匹配元素的索引
    public static List<Integer> findAllIndexes(int[] arr, int target) {
        List<Integer> indexes = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                indexes.add(i);
            }
        }
        return indexes;
    }
    // 查找所有匹配的对象
    public static <T> List<T> findAllMatches(T[] arr, T target) {
        List<T> matches = new ArrayList<>();
        for (T element : arr) {
            if (element.equals(target)) {
                matches.add(element);
            }
        }
        return matches;
    }
    public static void main(String[] args) {
        int[] numbers = {3, 7, 3, 9, 3, 11, 3};
        int target = 3;
        List<Integer> indexes = findAllIndexes(numbers, target);
        System.out.println("元素 " + target + " 出现的位置: " + indexes);
        System.out.println("共出现 " + indexes.size() + " 次");
        // 字符串数组查找示例
        String[] names = {"Alice", "Bob", "Alice", "Charlie", "Alice"};
        List<String> alices = findAllMatches(names, "Alice");
        System.out.println("找到 " + alices.size() + " 个 Alice");
    }
}
查找方法 时间复杂度 适用场景
线性查找 O(n) 小数组、未排序数组
二分查找 O(log n) 已排序的大数组
哈希查找 O(1) 需要频繁查找的场景
树查找 O(log n) 动态数据、需要排序

最佳实践建议

  1. 对于小数组(< 100个元素):使用线性查找
  2. 对于已排序的大数组:使用二分查找
  3. 频繁查找的场景:考虑使用HashMap或HashSet
  4. 对象数组:合理实现equals()和hashCode()方法
  5. 查找多个结果:返回List而不是单个元素

这些案例涵盖了Java中常见的数组查找场景,您可以根据实际需求选择合适的实现方式。

抱歉,评论功能暂时关闭!