/** * Map添加: * 1. 不能重复,存取顺序不一致 * 2. 若键不存在,指直接存储,返回null;若键已经存在,则替换原来的值,返回被替换的值 * @param args */
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, Integer> map = new HashMap();
//添加
Integer i1 = map.put("张三", 23); //null //若键不存在,指直接存储,返回null
Integer i2 = map.put("李四", 24); //null //若键已经存在,则替换原来的值,返回被替换的值
Integer i3 = map.put("王五", 25); //null
Integer i4 = map.put("赵六", 26); //null
Integer i5 = map.put("张三", 27); //23
System.out.println(map); //{李四=24, 张三=27, 王五=25, 赵六=26}
//删除
Integer value = map.remove("张三"); //根据键删除元素,返回键对应的值
System.out.println(value);//27
System.out.println(map);//{李四=24, 王五=25, 赵六=26}
//map.clear(); //清空
//判断
System.out.println(map.containsKey("张三")); //false //判断是否包含键
System.out.println(map.containsValue(24)); //true //判断是否包含值
System.out.println(map.isEmpty()); //false //判断是否为空
//获取
Set<String> s = map.keySet(); //获取集合中所有键的集合
System.out.println(s); //[李四, 王五, 赵六]
Collection<Integer> c = map.values(); //获取集合中所有值的集合
System.out.println(map.size()); //返回Map集合中键值对的个数
}
B:案例演示
Map集合的遍历之键找值
HashMap<String, Integer> hm = new HashMap<>();
hm.put("张三", 23);
hm.put("李四", 24);
hm.put("王五", 25);
hm.put("赵六", 26);
/*Set<String> keySet = hm.keySet(); //获取集合中所有的键
Iterator<String> it = keySet.iterator(); //获取迭代器
while(it.hasNext()) { //判断单列集合中是否有元素
String key = it.next(); //获取集合中的每一个元素,其实就是双列集合中的键
Integer value = hm.get(key); //根据键获取值
System.out.println(key + "=" + value); //打印键值对
}*/
for(String key : hm.keySet()) { //增强for循环迭代双列集合第一种方式
System.out.println(key + "=" + hm.get(key));
}
B:案例演示
Map集合的遍历之键值对对象找键和值
HashMap<String, Integer> hm = new HashMap<>();
hm.put("张三", 23);
hm.put("李四", 24);
hm.put("王五", 25);
hm.put("赵六", 26);
/*Set<Map.Entry<String, Integer>> entrySet = hm.entrySet(); //获取所有的键值对象的集合
Iterator<Entry<String, Integer>> it = entrySet.iterator();//获取迭代器
while(it.hasNext()) {
Entry<String, Integer> en = it.next(); //获取键值对对象
String key = en.getKey(); //根据键值对对象获取键
Integer value = en.getValue(); //根据键值对对象获取值
System.out.println(key + "=" + value);
}*/
for(Entry<String,Integer> en : hm.entrySet()) {
System.out.println(en.getKey() + "=" + en.getValue());
}
//这里直接写Entry也行,相当于直接使用子类对象;要是写Map.Entry相当于父类引用指向子类对象.
C:源码分析
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
//遍历1:
for(Character key : hm.keySet()){
System.out.println(key+"..."+hm.get(key));
}
System.out.println("-------------");
//遍历2:
for(Entry<Character, Integer> en:hm.entrySet()){
System.out.println(en.getKey()+"..."+en.getValue());
}
/** * HashMap集合键是Student,值是String的案例 * @param args */
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Student, String> hm = new HashMap<>();
hm.put(new Student("张三",23),"北京");
hm.put(new Student("赵四",24),"上海");
hm.put(new Student("王五",25),"杭州");
hm.put(new Student("赵六",26),"衡水");
hm.put(new Student("张三",23),"武强");
System.out.println(hm);
//结果:{Student [name=张三, age=23]=武强, Student [name=赵四, age=24]=上海, Student [name=赵六, age=26]=衡水, Student [name=王五, age=25]=杭州}
}
//Student重写HashCode()和equals()方法,自动生成即可
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
法一:
/** * TreeMap集合键是Student值是String的案例 * @param args */
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap<Student, String> tm = new TreeMap<Student, String>();
tm.put(new Student("张三",33),"北京");
tm.put(new Student("李四",13),"上海");
tm.put(new Student("王五",43),"杭州");
tm.put(new Student("赵六",23),"衡水");
System.out.println(tm);
}
public class Student implements Comparable<Student>{
private String name;
private int age;
。。。
@Override
@Override
public int compareTo(Student o) {
int num = this.age - o.age; //以年龄为主要条件
return num==0? this.name.compareTo(o.name):num;//以名字为次要条件
}
}
法二:
/** * TreeMap集合键是Student值是String的案例 * @param args */
public static void main(String[] args) {
// TODO Auto-generated method stub
//Demo1();
TreeMap<Student, String> tm = new TreeMap<Student, String>(new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().compareTo(s2.getName()); //以名字为主要条件
return num ==0 ? s1.getAge() - s2.getAge() : num; //以年龄为次要条件
}
});
tm.put(new Student("张三",33),"北京");
tm.put(new Student("赵四",13),"上海");
tm.put(new Student("王五",43),"杭州");
tm.put(new Student("赵六",23),"衡水");
System.out.println(tm);
}
private static void Demo1() {
TreeMap<Student, String> tm = new TreeMap<Student, String>();
tm.put(new Student("张三",33),"北京");
tm.put(new Student("赵四",13),"上海");
tm.put(new Student("王五",43),"杭州");
tm.put(new Student("赵六",23),"衡水");
System.out.println(tm);
}
/** * 需求:统计字符串中每个字符出现的次数 * @param args */
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "aasdsdasdfsdfe";
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
char[] arr = s.toCharArray();
for(char c : arr){
/*if(!hm.containsKey(c)){ hm.put(c, 1); }else{ hm.put(c, hm.get(c)+1); }*/
hm.put(c, !hm.containsKey(c)?1:hm.get(c)+1);
}
for(Character key : hm.keySet()){
System.out.println(key+"..."+hm.get(key));
}
System.out.println("-------------");
for(Entry<Character, Integer> en:hm.entrySet()){
System.out.println(en.getKey()+"..."+en.getValue());
}
}
A:面试题
HashMap和Hashtable的区别
HashMap是JDK1.2版本出现的,是线程不安全的,效率高
Hashtable不可以存储null键和null值,
public static <T> void sort(List<T> list)
public static <T> int binarySearch(List<?> list,T key)
public static <T> T max(Collection<?> coll)
public static void reverse(List<?> list)
public static void shuffle(List<?> list)
public static void main(String[] args){
ArrayList<String> list = new ArrayList<>();
list.add("c");
list.add("a");
list.add("g");
list.add("e");
Collections.sort(list); //1.对集合进行排序
System.out.println(list); //[a, c, e, g]
//2.二分查找(针对有序排列),若找到返回索引;若没有找到,返回-(插入的位置)-1。
//在进行此调用之前,必须根据列表元素的自然顺序对列表进行升序排序(通过 sort(List) 方法)。
//如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。
System.out.println(Collections.binarySearch(list, "b"));//-2
System.out.println(Collections.binarySearch(list, "c"));//1
//3.最大值、最小值
System.out.println(Collections.max(list));//g
System.out.println(Collections.min(list));//a
//4.反转
Collections.reverse(list);
System.out.println(list);//[g, e, c, a]
//5.随机排序,可以用来洗牌
Collections.shuffle(list);
System.out.println(list);
}
A:案例演示
模拟斗地主洗牌和发牌,牌没有排序
//买一副扑克
String[] num = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] color = {"方片","梅花","红桃","黑桃"};
ArrayList<String> poker = new ArrayList<>();
for(String s1 : color) {
for(String s2 : num) {
poker.add(s1.concat(s2));
}
}
poker.add("小王");
poker.add("大王");
//洗牌
Collections.shuffle(poker);
//发牌
ArrayList<String> gaojin = new ArrayList<>();
ArrayList<String> longwu = new ArrayList<>();
ArrayList<String> me = new ArrayList<>();
ArrayList<String> dipai = new ArrayList<>();
for(int i = 0; i < poker.size(); i++) {
if(i >= poker.size() - 3) {
dipai.add(poker.get(i));
}else if(i % 3 == 0) {
gaojin.add(poker.get(i));
}else if(i % 3 == 1) {
longwu.add(poker.get(i));
}else {
me.add(poker.get(i));
}
}
//看牌
System.out.println(gaojin);
System.out.println(longwu);
System.out.println(me);
System.out.println(dipai);
//买一副牌
String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] color = {"方片","梅花","红桃","黑桃"};
HashMap<Integer, String> hm = new HashMap<>(); //存储索引和扑克牌
ArrayList<Integer> list = new ArrayList<>(); //存储索引
int index = 0; //索引的开始值
for(String s1 : num) {
for(String s2 : color) {
hm.put(index, s2.concat(s1)); //将索引和扑克牌添加到HashMap中
list.add(index); //将索引添加到ArrayList集合中
index++;
}
}
hm.put(index, "小王");
list.add(index);
index++;
hm.put(index, "大王");
list.add(index);
//洗牌
Collections.shuffle(list);
//发牌
TreeSet<Integer> gaojin = new TreeSet<>();
TreeSet<Integer> longwu = new TreeSet<>();
TreeSet<Integer> me = new TreeSet<>();
TreeSet<Integer> dipai = new TreeSet<>();
for(int i = 0; i < list.size(); i++) {
if(i >= list.size() - 3) {
dipai.add(list.get(i)); //将list集合中的索引添加到TreeSet集合中会自动排序
}else if(i % 3 == 0) {
gaojin.add(list.get(i));
}else if(i % 3 == 1) {
longwu.add(list.get(i));
}else {
me.add(list.get(i));
}
}
//看牌
lookPoker("高进", gaojin, hm);
lookPoker("龙五", longwu, hm);
lookPoker("冯佳", me, hm);
lookPoker("底牌", dipai, hm);
}
public static void lookPoker(String name,TreeSet<Integer> ts,HashMap<Integer, String> hm) {
System.out.print(name + "的牌是:");
for (Integer index : ts) {
System.out.print(hm.get(index) + " ");
}
System.out.println();
}
public class Demo2_genric {
/** * ? super E 泛型固定下边界,,比如Student的比较器,BaseStudent也可以用(拿出来比较) * ? extends E 泛型固定上边界,,比如BaseStudent加入到Student中(放进去) * @param args */
public static void main(String[] args) {
//addAll(Collection<? extends E> c)
ArrayList<Student> list1 = new ArrayList<Student>();
list1.add(new Student("a",23));
list1.add(new Student("b",45));
ArrayList<BaseStudent> list2 = new ArrayList<>();
list2.add(new BaseStudent("a",23));
list2.add(new BaseStudent("b",45));
list1.addAll(list2);
//TreeMap(Comparator<? super K> comparator)
TreeSet<Student> ts = new TreeSet<>(new CompareByAge());
ts.add(new Student("a",23));
ts.add(new Student("b",45));
ts.add(new Student("c",25));
TreeSet<BaseStudent> ts1 = new TreeSet<>(new CompareByAge());
ts1.add(new BaseStudent("a",23));
ts1.add(new BaseStudent("b",45));
ts1.add(new BaseStudent("c",25));
System.out.println(ts1);
//在这里,比较器是Student的,但是BaseStudent也能用
}
}
class CompareByAge implements Comparator<Student>{
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() -s2.getAge();
return num==0?s1.getName().compareTo(s2.getName()):num;
}
}