本帖最后由 马镱洵 于 2012-10-14 22:45 编辑
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- public class PokerTest {
- public static void main(String[] args) {
- String[] numall = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J",
- "Q", "K", "A" };
- String[] hsall = { "黑桃", "红桃", "方块", "梅花" };
- List li = new ArrayList();
- for (int i = 0; i < 4; i++) {
- for (int j = 0; j < 13; j++) {
- Poker po = new Poker(hsall[i], numall[j]);
- li.add(po);
- }
- }
- Random ran = new Random();
- // List li1 = li.subList(0, 26);
- // List li2 = li.subList(26, 52); // 把集合分成两个li1和li2,每个的元素各26个
- <FONT color=red> // 注意了, 通过li.subList()方法返回的是li的一个子List,不能对子List调用add()与remove()
- // 方法,否则就会抛出并发异常.所以要对List进行add与remove操作的话,就要重新构造集合 对象.
- </FONT> List li1 = new ArrayList(li.subList(0, 26));
- List li2 = new ArrayList(li.subList(0, 26)); for (int l = 0; l < li1.size(); l++) {
- int i = ran.nextInt(26);
- int j = ran.nextInt(26);
- int k = ran.nextInt(26);
- Object p1 = li1.get(i); // 从li1中随机位置取一个元素p1
- Object p2 = li2.set(j, p1); // 把p1和li2中随机位置的p2交换
- li1.remove(p1); // 把p1从原集合li1移除
- li1.add(k, p2); // 把p2插入li1随机位置
- }
- List list = new ArrayList();
- list.addAll(li1);
- list.addAll(li2);
- System.out.println(list);
- }
- }
- class Poker {
- String num;
- String hs;
- public Poker(String hs, String num) {
- this.num = num;
- this.hs = hs;
- }
- public String toString() {
- return hs + num;
- }
- }
复制代码 |