开发者

Accessing variable from different method

Java Day 1 from c#. Just playing around with java (just for fun) and thought this example was interesting, the thing that gets me is how does bubblesort method access intArray? ok I know its being passed as a variable.. but its modifying the original array? I could understand of the bubblesort method printed the new array, but its the original method? Cool, but now sure how/why this is allowed? (hope I explained this properly)

public class HelloWorld {

public static void main(String[] args) {

    //create an int array we want to sort using bubble sort algorithm
    int intArray[] = new int[]{5,90,35,45,150,3};

    //print array before sorting using bubble sort algorithm
    System.out.println("Array Before Bubble Sort");
    for(int i=0; i < intArray.length; i++)
        System.out.print(intArray[i] + " ");

    //sort an array in descending order using bubble sort algorithm
    bubbleSort(intArray);

    System.out.println("");

    //print array afte开发者_如何学Gor sorting using bubble sort algorithm
    System.out.println("Array After Bubble Sort");
    for(int i=0; i < intArray.length; i++)
        System.out.print(intArray[i] + " ");

    }

    private static void bubbleSort(int[] intArray){

    int n = intArray.length;
    int temp = 0;

    for(int i=0; i < n; i++){
        for(int j=1; j < (n-i); j++){

            if(intArray[j-1] < intArray[j]){
                //swap the elements!
                temp = intArray[j-1];
                intArray[j-1] = intArray[j];
                intArray[j] = temp;
            }
        }
    }        
    }
}


Arrays are object types in Java, and so are accessed by reference. You pass a reference* to the original array when you call the method, so the method accesses (and modifies) the original array.


* To all the sharp-eyed pedants, I'm being very careful to avoid the "you pass by reference in Java" fallacy.


Strictly talking, you are not modifying the array, you are moving its contents within positions

[1,3,2,4] => [1,2,3,4] is the same 4 lenght array but the content of the 2nd and 3rd position got they value changed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜