java中 数组可以作为形式参数传递到调用的方法中吗?要怎么操作?
可以,操作代码如下:
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">
}
2.数组可以作为参数传递到方法中,例如
public void method1(int[] arr){
//your code block
}
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 void print(String[] a)
{
for(String tmp:a){
System.out.println(a);
}
}
public static void main(String[] str){
String[] s={"1","2","3"};
Test t=new Test();
t.print(s);
}
}
{
for(String tmp:a){
System.out.println(a);
}
}