集合的框架
Collection集合:是跟接口,有两个重要的子接口,分别是List和Set
List接口存储数据的时候有什么特点:有序的可以重复的
Se接口存储数据的时候又是什么特点:无序的不可重复的
Collection接口下面的方法:
public boolean add(E e);添加元素 public void clear();清空 public boolean remove(E e);指定的元素删除掉 public int size();返回集合中元素的个数 public Object[] toArray();把集合中的元素存到数组里面。
经典案例
按照斗地主的规则,完成洗牌发牌的动作。
import java.util.ArrayList;
import java.util.Collections;
public class Poker {
public static void main(String[] args) {
//1.创建一个容器用来保存牌面的
ArrayList<String> pokerBox = new ArrayList<String>();
//2.创建花色容器
ArrayList<String> colors = new ArrayList<String>();
//3.创建数字的容器
ArrayList<String> numbers = new ArrayList<String>();
//4.将花色添加到集合中 ♣♠♥
colors.add("♥");
colors.add("♦");
colors.add("♠");
colors.add("♣");
//5.将数字添加到数字集合中
for (int i = 2; i <= 10; i++) {
numbers.add(i+"");//将int类型的数据转为String类型的数据咋转
}
numbers.add("J");
numbers.add("Q");
numbers.add("K");
numbers.add("A");
//6.通过数字集合和花色集合创造出来牌
//拿一个花色,然后跟每一个数字进行集合存储到pokerBox集合中
for (String color : colors) {//4
//遍历的是每一次的花色
for (String number : numbers) {//13
//结合
String card = color + number;
//存储到咱们牌盒集合中
pokerBox.add(card);//pokerBox存了52个
}
}
//7.大王小王也存进去
pokerBox.add("小王");
pokerBox.add("大王");
//因为list集合是有序的 add的时候有序的
System.out.println(pokerBox);
//可以打乱
//8洗牌
Collections.shuffle(pokerBox);//对列表中的元素进行随机打乱
System.out.println(pokerBox);
//9.发牌 三个玩家 还有一个底牌 展示一下即可
ArrayList<String> player1 = new ArrayList<String>();
ArrayList<String> player2 = new ArrayList<String>();
ArrayList<String> player3 = new ArrayList<String>();
ArrayList<String> dipai = new ArrayList<String>();
//10.遍历总牌数
for (int i = 0; i < pokerBox.size(); i++) {
//获取牌面 随机打乱了
String card = pokerBox.get(i);//获取了所有牌
//留出三张底牌存到底牌集合中
if (i >= 51) {//存到底牌中
dipai.add(card);
}else {
//发给三个人 集合 依次的发牌
if (i % 3 == 0) {
player1.add(card);
} else if (i % 3 == 1) {
player2.add(card);
} else {
player3.add(card);
}
}
}
//看牌
System.out.println("啥的:" + player1);
System.out.println("建国后:" + player2);
System.out.println("厄尔:" + player3);
System.out.println("iy:" + dipai);
}
}