Java学习第八周
1.Map集合概述,特点,功能
Map接口概述
将键映射到值的对象
一个映射不能包含重复的键
每个键最多只能映射到一个值
Map接口和Collection接口的不同
Map是双列的,Collection是单列的
Map的键唯一,Collection的子体系Set是唯一的
Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效
功能:
a:添加功能
V put(K key,V value):添加元素。这个其实还有另一个功能替换(键相同 值覆盖)
如果键是第一次存储,就直接存储元素,返回null
如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
b:删除功能
void clear():移除所有的键值对元素
V remove(Object key):根据键删除键值对元素,并把值返回
c:判断功能
boolean containsKey(Object key):判断集合是否包含指定的键
boolean containsValue(Object value):判断集合是否包含指定的值
boolean isEmpty():判断集合是否为空
d:获取功能
Set<Map.Entry<K,V>> entrySet(): 返回一个键值对的Set集合
V get(Object key):根据键获取值
Set keySet():获取集合中所有键的集合
Collection values():获取集合中所有值的集合
e:长度功能
int size():返回集合中的键值对的对数
2.遍历方式:
①Map集合的遍历之键找值
②Map集合的遍历之键值对对象找键和值
3. TreeMap集合框架
TreeMap 键不允许插入null键
TreeMap: 键的数据结构是红黑树,可保证键的排序和唯一性
排序分为自然排序和比较器排序(注意键要实现Comparable 接口或者使用匿名内部类)
线程是不安全的效率比较高
4.HashMap和Hashtable的区别
HashMap: 线程不安全,效率高.允许null值和null键
Hashtable: 线程安全 , 效率低.不允许null值和null键
5.Collections工具类
Collections类概述: 针对集合操作 的工具类
:Collections成员方法
public static void sort(List list): 排序,默认按照自然顺序
public static int binarySearch(List<?> list,T key): 二分查找
public static T max(Collection<?> coll): 获取最大值
public static void reverse(List<?> list): 反转
public static void shuffle(List<?> list): 随机置换
6.斗地主案例
public class DoudizhuDemo {
public static void main(String[] args) {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
ArrayList<Integer> array = new ArrayList<Integer>();
String[] colors = { "♠", "♥", "♣", "♦" };
String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",
"K", "A", "2", };
int index = 0;
for (String number : numbers) {
for (String color : colors) {
String poker = color.concat(number);
hm.put(index, poker);
array.add(index);
index++;
}
}
hm.put(index, "小王");
array.add(index);
index++;
hm.put(index, "大王");
array.add(index);
Collections.shuffle(array);
TreeSet<Integer> a = new TreeSet<Integer>();
TreeSet<Integer> b = new TreeSet<Integer>();
TreeSet<Integer> c = new TreeSet<Integer>();
TreeSet<Integer> d = new TreeSet<Integer>();
for (int x = 0; x < array.size(); x++) {
if (x >= array.size() - 3) {
a.add(array.get(x));
} else if (x % 3 == 0) {
b.add(array.get(x));
} else if (x % 3 == 1) {
c.add(array.get(x));
} else if (x % 3 == 2) {
d.add(array.get(x));
}
}
// 看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)
lookPoker("底牌", a, hm);
lookPoker("B", b, hm);
lookPoker("C", c, hm);
lookPoker("D", d, hm);
}
// 写看牌的功能
public static void lookPoker(String name, TreeSet<Integer> ts,
HashMap<Integer, String> hm) {
System.out.print(name + "的牌是:");
for (Integer key : ts) {
String value = hm.get(key);
System.out.print(value + " ");
}
System.out.println();
}
}