Map
Map集合的概述和使用
- 概述:
- Interface Map<K,V> K:键的类型;V:值的类型
- 将键映射到值的对象;不能包含重复的键;每个键最多可以映射一个值;
- 创建Map集合对象:
- 多态的方式
Map<String,Sting> map = new HashMap<String,Sting>();
map.put("张良","19");
- 具体实现类HashMap
HashMap:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
Map集合的基本功能
Map集合的获取功能:
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("hello","world");
map.put("张良","19");
//根据键获取值
System.out.println(map.get("hello"));
//获取键
Set<String> keySet = map.keySet();
System.out.println(keySet);
//获取值
Collection<String> values = map.values();
System.out.println(values);
System.out.println(map);
}
Map集合的遍历
方法一:
方法二:
//遍历方法一
Set<String> keySet = map.keySet();
for(String key:keySet){
String value = map.get(key);
System.out.println(key+","+value);
}
System.out.println("-------");
//遍历方法二 //获取集合
Set<Map.Entry<String, String>> entries = map.entrySet();
//获取集合对象
for(Map.Entry<String, String> s:entries){
String key = s.getKey();
String value = s.getValue();
System.out.println(key+","+value);
}
System.out.println("-------");
Collections
Collections的概述
- 是针对集合的工具类
- 此类仅由静态方法组合或返回集合(将来可以通过类名调用方法)
Collection与Collections的区别:
帮助文档分析:
public class Collections extends Object
-----
public interface Collection<E> extends Iterable<E>
常用方法
- public static <T extends Comparable<? super T>> void sort(List list);按照升序排列指定的列表。
- public static void reverse(List<?> list)反转指定列表中元素的顺序。
- public static void shuffle(List<?> list,Random rnd)使用指定的随机源随机排列指定的列表。