JAVA基础集合应用练习题,结合list set ,map集合,Collections工具类
定义两个字符串数组:
String[] s1 = {"♡", "♤", "♢", "♣"};
String[] s2 = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A",};
List<Integer> list = new ArrayList<>();
Map<Integer, String> map = new TreeMap<>();
list存入编号作为map集合的健存入map集合中
牌型和牌进行拼接存入map集合作为值
使用循环嵌套
int count = 0;
for (String s : s1) {
for (String s3 : s2) {
map.put(count, s + s3);
list.add(count);
count++;
}
}
单独存储大小王
map.put(count, "大王");
list.add(count);
count++;
map.put(count, "小王");
list.add(count);
count++;
//工具类,自行查找api, 此方法是打乱集合中的排序,map集合的特性是根据
//键找值,打乱list集合的元素即可(编号当做值已经存入了map集合)
**Collections.shuffle(list);**
//定义三个玩家集合和一个底牌集合:
Set<Integer> aaa = new TreeSet<>();
Set<Integer> bbb = new TreeSet<>();
Set<Integer> ccc = new TreeSet<>();
Set<Integer> ddd = new TreeSet<>();
for (int i = 0; i < list.size(); i++) {
int a = list.get(i);
if (i >= list.size() - 3) {//当循环等于list集合的总长度就让牌发入底牌,让集合长度-3.
ddd.add(a);
//让集合元素对3取余,分别发给三个集合(这里是三个玩家所以对3取余,如多是4个就对4取余即可,以此类推)
} else if (i % 3 == 0) {
aaa.add(a);
} else if (i % 3 == 1) {
bbb.add(a);
} else if (i % 3 == 2) {
ccc.add(a);
}
}
kp(“eee”,aaa,map);
kp(“eee”,bbb,map);
kp(“eee”,ccc,map);
kp(“eee”,ddd,map);
此处代码只是为了方便看牌定义的看牌方法值得注意的是,集合作为参数进行传递的时候需要注意,定义集合的时候 = 等号左边定义的是什么类型的集合,作为参数的时候就要是什么类型的.例如:定义的是set集合,作为参数的时候确实TreeSet这样的参数是不可行的,代码编译时期就回报错
private static void kp(String name, Set<Integer> ts, Map<Integer, String> mp) {
System.out.print(name + "牌是");
for (Integer t : ts) {
String s = mp.get(t);
System.out.print(s);
}
System.out.println();
}