在使用List等集合和数组作为函数参数时一定是进行地址引用传递的,所以在我们自己写函数方法时可以直接将我们主函数main中要进行操作的集合或者数组直接作为实参传递给定义的函数进行处理,不用设置返回值,直接将返回值弄成void类型即可,当然也可以设置成跟实参返回类型一样的类型,两个方法其实都可以,只是本质上都是类似c语言中的指针操作,怎么改变都是对地址值所对应的内容进行操作。例如(部分函数):
//洗牌的功能1
public static void shufflePoker(LinkedList pokers){
//创建随机数对象
Random random = new Random();
for(int i = 0 ; i <100; i++){
//随机产生两个索引值
int index1 = random.nextInt(pokers.size());
int index2 = random.nextInt(pokers.size());
//根据索引值取出两张牌,然后交换两张牌的顺序
Poker poker1 = (Poker) pokers.get(index1);
Poker poker2 = (Poker) pokers.get(index2);
pokers.set(index1, poker2);
pokers.set(index2, poker1);
}
}
//洗牌2
public static LinkedList randompoker(LinkedList listtwo)
{
for(int i = 0; i < 100; i++)
{
Random random = new Random();
int a = random.nextInt(listtwo.size());
int b = random.nextInt(listtwo.size());
Poker p = (Poker)listtwo.get(a);
listtwo.set(a, listtwo.get(b));
listtwo.set(b, p);
}
return listtwo;
}
但是其实第一种反而会好点,起码目前根据自己所学的是能节省内存
原文:http://www.cnblogs.com/bravejia/p/4984499.html