Thinking in java-33 Collection & Map

本文通过具体示例介绍Java中Map容器的使用方法及常见操作,包括如何创建HashMap实例、增删改查等基本操作,并展示了两种遍历Map的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Collection & Map 图示

这里写图片描述

  • 图示中,虚线包围的是interface,实线所包围的是具体的容器类。
  • Comparable:对应于给定类对应元素实现int comparaTo(Object obj)。
  • Comparator:Comparator对应的是int comparable(Object obj1, Object obj2)在使用Collections.sort(Collection c, Comparator comparator)。
  • Collections & Arrays:对应的是工具类,提供了一些诸如排序之类的算法。
  • Iterable & Iterator:两者都是接口。任意实现了Iterable接口的类都可以使用foreach语句;而Iterator接口extends Iterable接口。
  • 一些常见的关于map的函数:
Map<K,V> map = new HashMap<>();
Set<Map.Entry<K,V>> set = map.entrySet();   //Elements stored in the set is an entry
map.keySet();   //a set of map's key
map.values();   //return Collection object.

2. Map详解

package com.fqy.blog;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;

class Faculty {
    private String name;

    public Faculty(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class MapDemo {
    public static void main(String[] args) {
        Random random = new Random();

        Faculty f1 = new Faculty("a");
        Faculty f2 = new Faculty("b");
        Faculty f3 = new Faculty("c");
        Faculty f4 = new Faculty("d");
        Faculty f5 = new Faculty("e");

        // Default value of object array is NULL
        Integer[] arr = new Integer[5];
        for (int i = 0; i < arr.length; i++)
            arr[i] = random.nextInt(100) * (random.nextBoolean() ? 1 : -1);

        Map<Faculty, Integer> map = new HashMap<>();
        map.put(f1, arr[0]);
        map.put(f2, arr[1]);
        map.put(f3, arr[2]);
        map.put(f4, arr[3]);
        map.put(f5, arr[4]);

        Set<Faculty> set = map.keySet();
        Set<Map.Entry<Faculty, Integer>> entrySet = map.entrySet();
        Collection<Integer> c = map.values();

        System.out.println(c);

        for (Faculty f : set)
            System.out.print(f + " ");
        System.out.println();

        for (Map.Entry<Faculty, Integer> entry : entrySet)
            System.out.print(entry + " ");
        System.out.println();

        // Iteration 1:
        for (Faculty f : set)
            System.out.print(map.get(f) + " ");
        System.out.println();
        // Iteration 2:
        for (Map.Entry<Faculty, Integer> entry : map.entrySet())
            System.out.print(entry.getKey() + "->" + entry.getValue() + " ");
        System.out.println();

    }
}
//Running result:
[-93, -34, -79, 70, -14]
c d b a e 
c=-93 d=-34 b=-79 a=70 e=-14 
-93 -34 -79 70 -14 
c->-93 d->-34 b->-79 a->70 e->-14 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值