繁体   English   中英

如何实现void方法而不是返回某些东西的方法?

[英]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 [] ,但您可以更改numbersints

具有返回类型的函数执行某些操作(执行代码)并将一些结果返回给调用该函数的代码。 没有返回类型的函数执行一些代码但不返回结果(因为在大多数情况下不需要它)

考虑这两个功能:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM