在使用setFish()方法后,lake对象的成员变量fish的值变为了对象redFish,然后foodFish()方法让对象fish (也就是redFish对象)的成员变量weight变为了121;
通过打印下各方法中对象redFish和对象lake.fish的地址,发现都是一样的,它们都是指向同一个对象,所以其成员变量的值也会是一样的。
测试代码如下:
参考链接:
https://blog.csdn.net/qq_21963133/article/details/80624091
class Fish{
int weight=1;
}
class Lake{
Fish fish;
void setFish(Fish s) {
fish=s;
System.out.println("in setFish() , 对象fish的地址是:"+ System.identityHashCode(fish));
System.out.println("in setFish() , fish.weight="+fish.weight+"\n");
}
void foodFish(int m) {
fish.weight=fish.weight+m;
System.out.println("in foodFish() , 对象fish的地址是:="+System.identityHashCode(fish));
System.out.println("in foodFish() , fish.weight="+fish.weight+"\n");
}
}
public class E {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fish redFish = new Fish();
// https://blog.csdn.net/qq_21963133/article/details/80624091
//System.out.println("in setFish() , redFish.hashCode()="+redFish.hashCode());
System.out.println("in main , 对象redFish的地址是:"+System.identityHashCode(redFish));
System.out.println("in main , redFish.weight="+redFish.weight+"\n");
Lake lake = new Lake();
lake.setFish(redFish);
lake.foodFish(120);
//System.out.println(redFish.weight);
System.out.println("in main , 对象redFish的地址是:"+System.identityHashCode(redFish));
System.out.println("in main , redFish.weight="+redFish.weight+"\n");
// System.out.println(lake.fish.weight);
System.out.println("in main ,对象lake.fish的地址"+System.identityHashCode(lake.fish));
System.out.println("in main , lake.fish.weight="+lake.fish.weight+"\n");
}
}
该段代码实现的是斗地主发牌程序。其中,代码一共包括以下五个部分:
1.准备54张牌
定义HashMap集合p来存储牌的索引和组装好的牌,定义ArrayList集合pIndex来存储牌的索引(0~53)。之后,定义colors和numbers两个List集合,分别为扑克牌的花色和序号,用双重循环嵌套遍历两个集合,组装出52张牌,然后将大王和小王加入到集合中,完成了54张牌的组装。
2.洗牌
使用Collections的方法shuffle(pIndex)将牌的索引打乱,保证牌的顺序被随机打乱。
3.发牌
定义四个集合,分别存储3个玩家的牌和底牌。遍历存储牌索引的list集合pIndex,获取每一个牌的索引。如果为最后的三张底牌,就给底牌集合d发牌;否则,将牌均匀发给三个玩家。
4.排序
用Collections的方法sort(List)对发给三个玩家的牌进行排序,保证发给三个玩家的牌有序排列。
5.看牌
定义一个lookP的方法,用来展示发牌后三个玩家手上的牌和底牌。遍历存储玩家牌索引的list集合,获取每一个牌的索引。通过牌的索引从HashMap集合p中取出对应的牌。