首页 热点资讯 义务教育 高等教育 出国留学 考研考公

在java中,如何将方法作为参数传递

发布网友 发布时间:2022-04-21 21:43

我来回答

1个回答

热心网友 时间:2023-07-18 11:00

可以,操作代码如下:

public class ArrTest{

public static void doTest(String[] args){

for(int i=0;i<args.length;i++){

System.out.println(args[i]);

}

}

public static void main(String[] args){

String[] testArr = {"a","b","c","d"};

ArrTest.doTest(testArr );

}

}

扩展资料:

把数组作为参数传入一个方法,在该方法中对数组进行一些操作:如果仅仅是插入数据项等一般操作,那么该操作会影响到数组本身;反之,如调整数组大小、对数组赋值等操作,则对数组本身没有影响。

例子:

public class Tester {<br data-filtered="filtered">

public static void counter(int count) {<br data-filtered="filtered">

count = 2;<br data-filtered="filtered">

}<br data-filtered="filtered">

<br data-filtered="filtered">

public static void changeA1(int[] ints) {<br data-filtered="filtered">

int[] temp = { 4, 5, 6 };<br data-filtered="filtered">

ints = temp;<br data-filtered="filtered">

}<br data-filtered="filtered">

<br data-filtered="filtered">

public static void changeA2(int[] ints) {<br data-filtered="filtered">

ints[0] = 4;<br data-filtered="filtered">

ints[1] = 5;<br data-filtered="filtered">

ints[2] = 6;<br data-filtered="filtered">

}<br data-filtered="filtered">

<br data-filtered="filtered">

public static void main(String[] args) {<br data-filtered="filtered">

// Output: 1<br data-filtered="filtered">

// 基本数据类型没有改变。<br data-filtered="filtered">

int count = 1;<br data-filtered="filtered">

counter(count);<br data-filtered="filtered">

System.out.println("count: " + count);<br data-filtered="filtered">

<br data-filtered="filtered">

<br data-filtered="filtered">

int[] ints = { 1, 2, 3 };<br data-filtered="filtered">

<br data-filtered="filtered">

// Output: 1, 2, 3<br data-filtered="filtered">

// 对数组赋值,不会改变原始数组。<br data-filtered="filtered">

changeA1(ints);<br data-filtered="filtered">

for (int i = 0; i < ints.length; i++) {<br data-filtered="filtered">

System.out.print(ints[i] + " ");<br data-filtered="filtered">

}<br data-filtered="filtered">

<br data-filtered="filtered">

// Output: 4, 5, 6<br data-filtered="filtered">

// 可以对数组插入新的数据项。<br data-filtered="filtered">

System.out.println();<br data-filtered="filtered">

changeA2(ints);<br data-filtered="filtered">

for (int i = 0; i < ints.length; i++) {<br data-filtered="filtered">

System.out.print(ints[i] + " ");<br data-filtered="filtered">

}<br data-filtered="filtered">

}<br data-filtered="filtered">

}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com