MST

星途 面试题库

面试题:Java集合框架中如何利用策略设计模式优化排序操作

在Java集合框架中,`List`有多种排序方式。请阐述如何运用策略设计模式,针对不同类型的`List`元素(如自定义对象)实现灵活、可复用的排序策略。要求详细说明策略接口的设计、具体策略类的实现以及如何在集合的排序操作中应用这些策略。
11.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

策略接口设计

  1. 首先定义一个策略接口,该接口包含一个排序方法。以对自定义对象的List排序为例,假设自定义对象为Person,包含nameage属性。
public interface SortingStrategy<T> {
    int compare(T o1, T o2);
}

具体策略类实现

  1. 按年龄升序排序策略
public class AgeAscendingStrategy implements SortingStrategy<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.getAge() - p2.getAge();
    }
}
  1. 按名字字母顺序排序策略
public class NameAlphabeticalStrategy implements SortingStrategy<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.getName().compareTo(p2.getName());
    }
}

在集合排序操作中应用策略

  1. 假设Person类定义如下:
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
  1. 使用策略进行排序:
import java.util.ArrayList;
import java.util.List;

public class SortingApp {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 20));
        people.add(new Person("Charlie", 30));

        // 使用年龄升序策略排序
        SortingStrategy<Person> ageAscendingStrategy = new AgeAscendingStrategy();
        sortList(people, ageAscendingStrategy);
        System.out.println("按年龄升序排序: " + people);

        // 使用名字字母顺序策略排序
        SortingStrategy<Person> nameAlphabeticalStrategy = new NameAlphabeticalStrategy();
        sortList(people, nameAlphabeticalStrategy);
        System.out.println("按名字字母顺序排序: " + people);
    }

    private static <T> void sortList(List<T> list, SortingStrategy<T> strategy) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = 0; j < list.size() - i - 1; j++) {
                if (strategy.compare(list.get(j), list.get(j + 1)) > 0) {
                    T temp = list.get(j);
                    list.set(j, list.get(j + 1));
                    list.set(j + 1, temp);
                }
            }
        }
    }
}

在上述代码中,通过定义SortingStrategy接口来抽象排序策略,具体的排序策略类实现该接口的compare方法。在sortList方法中,根据传入的不同策略对象,对List进行不同方式的排序,从而实现了灵活、可复用的排序策略。