一、参数传递机制
Java方法的传递只有一种:值传递(方法内操作的是传入参数的复制)
因此,基本类型的数值交换不能通过方法来实现
package net.csdn.blog;
public class ForValidating
{
public static void main(String[] args)
{
int first = 5;
int second = 9;
System.out.println(first + " , " + second);//5 , 9
Swap.swap(first, second);
System.out.println(first + " , " + second);//5 , 9
}
}
class Swap
{
static void swap(int first, int second)
{
int temp = first;
first = second;
second = temp;
}
}
二、通过其他方式实现值交换的方法
用类包装
package net.csdn.blog;
public class ForValidating
{
public static void main(String[] args)
{
Hold hold = new Hold();
hold.first = 5;
hold.second = 9;
System.out.println(hold.first + " , " + hold.second);//5 , 9
Swap.swap(hold);
System.out.println(hold.first + " , " + hold.second);//9 , 5
}
}
class Hold
{
public int first;
public int second;
}
class Swap
{
static void swap(Hold hold)
{
int temp = hold.first;
hold.first = hold.second;
hold.second = temp;
}
}
用内置的Holder类
package net.csdn.blog;
import org.omg.CORBA.IntHolder;
/*
注意不能用各种包装类,它们都是final类,不可变,即使是引用类型,也不能实现交换
*/
public class ForValidating
{
public static void main(String[] args)
{
IntHolder first = new IntHolder(5);
IntHolder second = new IntHolder(9);
System.out.println(first.value + " , " + second.value);
Swap.swap(first, second);
System.out.println(first.value + " , " + second.value);
}
}
class Swap
{
static void swap(IntHolder first, IntHolder second)
{
int temp = first.value;
first.value = second.value;
second.value = temp;
}
}
Java里除了基本数据类型,就是引用类型,之所以用引用就能实现交换,是因为引用对象的名字相当于C++里面的指针
IntHolder first = new IntHolder(5);
first相当于一个指针,指向存放着5的内存,就算通过值传递,也相当于方法里只是复制了引用,复制的引用也是指向同一内存,可以实现修改
三、形参不确定的方法(两种)
package net.csdn.blog;
public class ForValidating
{
public static void main(String[] args)
{
String first_result = Uncertain.first_kind(1, "a", "b", "c");
String second_result = Uncertain.second_kind(2, new String[]{"d", "e", "f"});
System.out.println(first_result);//1( a b c )
System.out.println(second_result);//2( d e f )
String first_another_result = Uncertain.first_kind(3, new String[]{"g", "h", "i"});
System.out.println(first_another_result);//3( g h i )
}
}
class Uncertain
{
static String first_kind(int id, String ... property)
{
String result = id + "( ";
for(String s : property)
result += s + " ";
result += ")";
return result;
}
static String second_kind(int id, String[] property)
{
String result = id + "( ";
for(String s : property)
result += s + " ";
result += ")";
return result;
}
}
first_kind既可以传入多个参数,也可以直接传入一个数组,长度可变的形参只能处于参数列表的最后,且只能有一个
second_kind只能传入一个数组,但是可以定义多个,也可以放在参数列表的任何位置