Java基础之集合4

来源:互联网 发布:飞控编程用什么语言 编辑:程序博客网 时间:2024/06/05 20:30

1:Map

将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。 
Map和Collection的区别?
A:Map 存储的是键值对形式的元素,键唯一,值可以重复。
B:Collection 存储的是单独出现的元素,子接口Set元素唯一,子接口List元素可重复。

Map集合的遍历
A:键找值
a:获取所有键的集合
b:遍历键的集合,得到每一个键
c:根据键到集合中去找值

B:键值对对象找键和值
a:获取所有的键值对对象的集合
b:遍历键值对对象的集合,获取每一个键值对对象
c:根据键值对对象去获取键和值

代码
Map<String,String> hm = new HashMap<String,String>();

hm.put("it002","hello");
hm.put("it003","world");
hm.put("it001","java");

//方式1 键找值
Set<String> set = hm.keySet();
for(String key : set) {
String value = hm.get(key);
System.out.println(key+"---"+value);
}

//方式2 键值对对象找键和值
Set<Map.Entry<String,String>> set2 = hm.entrySet();
for(Map.Entry<String,String> me : set2) {
String key = me.getKey();
String value = me.getValue();
System.out.println(key+"---"+value);
}


2:Collections
(1)是针对集合进行操作的工具类
(2)Collection和Collections的区别
A:Collection 是单列集合的顶层接口,有两个子接口List和Set
B:Collections 是针对集合进行操作的工具类,可以对集合进行排序和查找等
(3)常见的几个小方法:
A:public static <T> void sort(List<T> list)
B:public static <T> int binarySearch(List<?> list,T key)
C:public static <T> T max(Collection<?> coll)
D:public static void reverse(List<?> list)
E:public static void shuffle(List<?> list)

模拟斗地主洗牌和发牌

程序代码:

package PocKet;

import java.util.ArrayList;
import java.util.Collections;

/*
 * 模拟斗地主洗牌和发牌
 * 
 * 分析:
 * A:创建一个牌盒
 * B:装牌
 * C:洗牌
 * D:发牌
 */
public class PockerDemo {
public static void main(String[] args) {
// 创建一个牌盒
ArrayList<String> array = new ArrayList<String>();

// 装牌
// 黑桃A,黑桃2,黑桃3,...黑桃K
// 红桃A,...
// 梅花A,...
// 方块A,...
// 定义一个花色数组
String[] colors = { "♠", "♥", "♣", "♦" };
// 定义一个点数数组
String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K" };
// 装牌
for (String color : colors) {
for (String number : numbers) {
array.add(color.concat(number));
}
}
array.add("小王");
array.add("大王");

// 洗牌
Collections.shuffle(array);

// System.out.println("array:" + array);

// 发牌
ArrayList<String> fengQingYang = new ArrayList<String>();
ArrayList<String> linQingXia = new ArrayList<String>();
ArrayList<String> liuYi = new ArrayList<String>();
ArrayList<String> diPai = new ArrayList<String>();

for (int x = 0; x < array.size(); x++) {
if (x >= array.size() - 3) {
diPai.add(array.get(x));
} else if (x % 3 == 0) {
fengQingYang.add(array.get(x));
} else if (x % 3 == 1) {
linQingXia.add(array.get(x));
} else if (x % 3 == 2) {
liuYi.add(array.get(x));
}
}


// 看牌
lookPoker("A", fengQingYang);
lookPoker("B", linQingXia);
lookPoker("C", liuYi);
lookPoker("底牌", diPai);
}


public static void lookPoker(String name, ArrayList<String> array) {
System.out.print(name + "的牌是:");
for (String s : array) {
System.out.print(s + " ");
}
System.out.println();
}
}

程序运行结果:



0 0