如何在Java中从另一个类依次调用带数字后缀的同名排序方法?
问题描述
我正在进行一项测试不同排序方法运行时长的学校项目,已获取包含sort1至sort5排序方法的类文件。在Driver类的sortTester方法的循环中,我需要依次调用这些方法,单个方法调用示例为sortItOut.sort1(randomIntsCopy);,现有代码如下,请协助实现循环调用:
import java.io.*; import java.security.SecureRandom; import java.time.Duration; import java.time.Instant; public class Driver { public static void main(String[] args) throws IOException { try { System.out.println(); } catch (ArrayIndexOutOfBoundsException e) { System.out.printf("%nError: When executing this program, please " + "enter the command followed by an integer that will determine " + "size of the array of random integers that is created.%n"); System.exit(0); // Terminates program } // Creates an integer, 'n', from command line argument Integer size = Integer.valueOf(args[0]); // Creates an array of size 'n' int[] randomInts = new int[size]; // Creates instance of SecureRandom class SecureRandom secureRandom = new SecureRandom(); // Populates the array with random integers for (int i = 0; i < randomInts.length; i++) { randomInts[i] = secureRandom.nextInt(); } int[] results = new int[5]; sortTester(randomInts, results); displayResults(size, results); // Outputs table of execution times } public static void sortTester(int[] randomInts, int[] results) { for (int i = 0; i < 5; i++) { System.out.printf("Sorting array with mystery sort %d...", i+1); // New copy of original randomInts array int[] randomIntsCopy = randomInts.clone(); Instant strtTime = Instant.now(); // Starts clock sortItOut.sort1(randomIntsCopy); // Sorts the array Instant endTime = Instant.now(); // Ends clock // Calculates the execution time for each iteration long time = (Duration.between(strtTime, endTime).toMillis()); int timeAsInt = (int) time; // Converts long -> int results[i] = timeAsInt; // Populates array with each duration System.out.printf(" Done!%n"); } } public static void displayResults(int size, int[] results) { System.out.printf("%n---------------------------%n"); System.out.printf("| %-9s | %6d |%n", " N ", size); System.out.printf("---------------------------%n"); for (int i = 0; i < 5; i++) { System.out.printf("| %-9s | %8d ms |%n", "sort" + (i+1) + "Time", results[i]); System.out.printf("---------------------------%n"); } System.out.println(); } }
解决方案
核心修改:循环调用排序方法
通过方法引用数组实现循环调用sort1到sort5,这种方式类型安全且代码简洁,修改后的sortTester方法如下:
public static void sortTester(int[] randomInts, int[] results) { // 定义方法引用数组,对应sort1至sort5 java.util.function.Consumer<int[]>[] sortMethods = (java.util.function.Consumer<int[]>[]) new java.util.function.Consumer[] { sortItOut::sort1, sortItOut::sort2, sortItOut::sort3, sortItOut::sort4, sortItOut::sort5 }; for (int i = 0; i < 5; i++) { System.out.printf("Sorting array with mystery sort %d...", i+1); int[] randomIntsCopy = randomInts.clone(); Instant strtTime = Instant.now(); // 调用对应索引的排序方法 sortMethods[i].accept(randomIntsCopy); Instant endTime = Instant.now(); long time = Duration.between(strtTime, endTime).toMillis(); results[i] = (int) time; System.out.printf(" Done!%n"); } }
额外优化:修复异常处理逻辑
原代码的try-catch块无法正确捕获命令行参数缺失或格式错误的异常,修改main方法的异常处理部分:
public static void main(String[] args) throws IOException { Integer size; try { // 将参数解析逻辑放入try块 size = Integer.valueOf(args[0]); } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) { System.out.printf("%nError: 执行程序时,请在命令后输入一个合法整数,用于指定随机数组的大小。%n"); System.exit(0); } // 后续数组初始化、填充等代码保持不变 int[] randomInts = new int[size]; SecureRandom secureRandom = new SecureRandom(); for (int i = 0; i < randomInts.length; i++) { randomInts[i] = secureRandom.nextInt(); } int[] results = new int[5]; sortTester(randomInts, results); displayResults(size, results); }
说明
- 方法引用
sortItOut::sortX要求sortX是静态方法,且参数为int[],与你的调用示例匹配;如果sortX是实例方法,需先创建sortItOut的实例,再使用new SortItOut()::sort1这类实例方法引用。 - 若不想使用方法引用,也可以用反射实现,但反射会增加代码复杂度且存在类型安全风险,不推荐用于此类简单场景。
内容的提问来源于stack exchange,提问作者Fuji
相关产品推荐
相关产品推荐

