挑战程序设计竞赛(算法和数据结构)——9.5 Java 中对应C++ STL中的Set,Map类

本文展示了Java编程中对Set和Map集合的基本操作,包括添加元素、删除元素、检查元素存在性以及遍历输出。示例中创建了一个HashSet并添加、移除元素,然后检查10是否存在于集合中。接着,通过HashMap展示了如何存储键值对,更新已存在的键值,并删除指定键的条目。
摘要由CSDN通过智能技术生成
import java.util.*;

public class SetAndMap {
    public static void main(String[] args) {
        System.out.println("---------Set部分-----------");
        HashSet<Integer> S = new HashSet<Integer>();
        S.add(8);
        S.add(1);
        S.add(7);
        S.add(4);
        S.add(8);
        S.add(4);

        printSet(S);

        S.remove(7);

        printSet(S);

        S.add(2);

        printSet(S);

        if(S.contains(10) == false) System.out.println("not found.");

        System.out.println("\n---------Map部分-----------");
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("red", 32);
        map.put("blue", 688);
        map.put("yello", 122);
        map.put("blue", map.get("blue") + 312);

        printMap(map);

        map.put("zebra", 101010);
        map.put("white", 0);
        map.remove("yello");

        printMap(map);
    }

    public static void printSet(HashSet/*也可以使用Set*/ set){
        Iterator<Integer> it = set.iterator();
        while(it.hasNext()){
            System.out.print(it.next() + " ");
        }
        System.out.println();
    }

    public static void printMap(HashMap<String, Integer>/*也可以使用Set*/ map){
        Set<String> key_set = map.keySet();
        System.out.println(map.size());
        Iterator<String> it = key_set.iterator();
        while(it.hasNext()){
            String key = it.next();
            int value = map.get(key);
            System.out.print(key + " --> " + value);
            System.out.println();
        }
        System.out.println();
    }



}

输出:

---------Set部分-----------
1 4 7 8 
1 4 8 
1 2 4 8 
not found.

---------Map部分-----------
3
red --> 32
blue --> 1000
yello --> 122

4
red --> 32
zebra --> 101010
blue --> 1000
white --> 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值