java-比较方法的更好方法是什么。 -2个示例

问题描述 投票:0回答:1

我有一些班上的比较方法,我不确定我应该做的方法

我提出的第一个选项

public static Comparator<Student> nameCompare(String str) { if (str.equals("ASC")) { return new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o2.getName().compareTo(o1.getName()); } }; } else { return new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getName().compareTo(o2.getName()); } }; } }

或最好使用此

public static Comparator<Student> nameCompare(String str) { return new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { if (str.equals("ASC")) // here would be the str purple and underline { return o2.getName().compareTo(o1.getName()); } else { return o1.getName().compareTo(o2.getName()); } } }; }

哪种选择会更好,或者说不同的选择是一种更正确的编码方法
因为第二个较短,但str将是紫色的,并下划线

java compare comparator
1个回答
0
投票
public static enum SortDirection { ASC, DESC }; public static Comparator<Student> nameCompare(SortDirection sortDirection) { return switch (sortDirection) { case ASC -> Comparator.comparing(Student::getName); case DESC -> Comparator.comparing(Student::getName).reversed(); case null -> throw new AssertionError(sortDirection); }; }


最新问题
© www.soinside.com 2019 - 2024. All rights reserved.