You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java数组排序:将排序逻辑封装为函数并调用的技术咨询

Fixing the Encapsulated Sorting Logic in Your Java Code

Hey there! I see you're trying to move your sorting logic into a separate method and ran into issues—let's get this sorted out (pun intended).

First, let's start with a complete, working version of your code with the sorting logic encapsulated properly:

import java.util.Arrays;

public class Sort {
    public static void main(String args[]){
        int [] array = new int[10];
        // Populate the array with random numbers
        for ( int i = 0 ; i < array.length ; i++ ) {
            array[i] = ((int)(Math.random()*100+1));
        }
        
        // Call our encapsulated sorting method
        sortArray(array);
        
        // Print the sorted array
        for ( int i = 0 ; i < array.length ; i++ ) {
            System.out.println(array[i]);
        }
    }
    
    // Encapsulated sorting method
    public static void sortArray(int[] inputArray) {
        // Arrays are passed by reference, so sorting this modifies the original array
        Arrays.sort(inputArray);
    }
}

Let's break down the common pitfalls that might have tripped you up:

  • Forgot the java.util.Arrays import: This is a super common mistake—Arrays.sort() lives in the java.util package, so you need that top-level import for the compiler to recognize the method.
  • Method accessibility mismatch: Since main() is a static method, you either need to make your sorting method static too (like the example above) or create an instance of the Sort class to call a non-static method. For a simple utility like this, static is the most straightforward choice.
  • Array pass-by-reference confusion: In Java, arrays are passed by reference. That means when you sort inputArray inside sortArray(), it directly modifies the original array you created in main(). If you want to keep the original unsorted array intact, you can adjust the method to return a sorted copy instead:
public static int[] sortArray(int[] inputArray) {
    // Create a copy to avoid modifying the original array
    int[] sortedArray = Arrays.copyOf(inputArray, inputArray.length);
    Arrays.sort(sortedArray);
    return sortedArray;
}

Then call it in main() like this:

int[] sortedArray = sortArray(array);
// Print sortedArray instead of the original array

If you hit a specific compiler error or runtime exception, feel free to share the details and we can dig deeper—but this should cover the most common issues when encapsulating this logic.

内容的提问来源于stack exchange,提问作者E.A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:19:16