[英]how to implement a void method as opposed to a method that returns something?
我只是考慮如何實現這兩種方法,如如何調用它們或使用它們? 由於第一個是無效的,它是如何工作的?
有人請使用和數組並為我實現這個或幫助我理解第一個void方法是如何工作的?
public static void insertionsort(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int copyNumber = numbers[i];
int j = i;
while (j > 0 && copyNumber < numbers[j-1]) {
numbers[j] = numbers[j-1];
j--;
}
numbers[j] = copyNumber;
}
}
public int[] InsertionSort(int[] data){
int len = data.length;
int key = 0;
int i = 0;
for(int j = 1;j<len;j++){
key = data[j];
i = j-1;
while(i>=0 && data[i]>key){
data[i+1] = data[i];
i = i-1;
data[i+1]=key;
}
}
return data;
}
在java中, 所有內容都按值傳遞,包括引用。 在void
方法中,傳遞對數組的引用的值。 因此,雖然您無法為numbers
分配新的int []
,但您可以更改numbers
的ints
。
具有返回類型的函數執行某些操作(執行代碼)並將一些結果返回給調用該函數的代碼。 沒有返回類型的函數執行一些代碼但不返回結果(因為在大多數情況下不需要它)
考慮這兩個功能:
public static int withResult( int someParameter)
{
//execute some code here
int someReturnValue = //result of the code above
return someReturnValue;
}
public static void withoutResult( int someParameter)
{
//execute some code here which produces no result which could be of interest to the caller (calling code)
} //end the function without returning anything
你會這樣稱呼它:
int result;
result = withResult( 1234 );//executes the function and stores its return type in 'result'
withResult( 468 );//executes the function but does not store the return type anywhere ("throws it away")
withoutResult ( 1234 );//simply executes the function
result = withoutResult ( 5678 ); //this makes no sense because the function does not return anything
返回void(即,不返回任何內容)的第一個方法是作為參數傳遞一個數組。 傳遞的是對聲明的數組的引用,並且在該方法之外分配內存。 該方法對該信息進行了分類; 當方法返回時,然后對該數組中的數據進行排序。
int[] myArray = getArrayInfo(); // assume this gets data in an array
WhateverClass.insertionSort(myArray); // this will sort that data
// at this point, myArray will be sorted
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.