Java集合容器


ArrayList

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in =new Scanner(System.in);
        ArrayList<String> s = new ArrayList<String>(); //定义两个类型,容器的类型,元素的类型
        s.add("Hello");  //向容器里添加元素
        s.add("world");
        s.add("!");
        s.add(1,"the"); //在指定位置中插入元素
        int index = in.nextInt();
        String p = null,q = null;
        if (index<s.size()) {
            p = s.get(index);  //返回容器中该位置的元素
            q = s.remove(index); //删除并返回容器中该位置的元素
        }
        System.out.println(p+" "+q);
        String[] a = new String[s.size()];
        s.toArray(a);  //将容器转换为数组
        System.out.println(Arrays.toString(a));
        System.out.println(s);  //直接输出容器
        System.out.println(s.size());  //容器的大小,里面有多少个元素
    }
}

输出为

2  //输入
world world
[Hello, the, !]
[Hello, the, !]
3

HashSet

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in =new Scanner(System.in);
        HashSet<String> s = new HashSet<String>(); //定义两个类型,容器的类型,元素的类型
        s.add("Hello");  //向容器里添加元素
        s.add("world");
        s.add("Hello");  //HashSet中不会出现重复元素,且元素无序
        String[] a = new String[s.size()];
        s.toArray(a);  //将容器转换为数组
        System.out.println(Arrays.toString(a));
        s.remove("Hello");  //删除容器中的指定元素
        System.out.println(s);  //直接输出容器
        System.out.println(s.size());  //容器的大小,里面有多少个元素
    }
}

输出为

[world, Hello]
[world]
1

HashMap

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in =new Scanner(System.in);
        HashMap<Integer, String> h = new HashMap<Integer, String>(); //定义三个类型,容器的类型,键的类型,值的类型
        h.put(1,"hello");  //向容器里添加键值对
        h.put(2,"the");
        h.put(3,"world");
        int index = in.nextInt();
        if (h.containsKey(index)) {  //判断键是否在容器里
            String a, b;
            a = h.get(index);   //得到容器中那个键所对应的值
            b = h.remove(index);  //删除容器中对应的键值对,并返回键所对应的值
            System.out.println(a + " " + b);
        }
        else{
            System.out.println("NOT FOUND");
        }
        for (int k : h.keySet()){   //将容器中的键单独取出做一个集合
            String s = h.get(k);
            System.out.println(s);
        }
        System.out.println(h);  //直接输出容器
        System.out.println(h.size()); //容器的大小,里面有多少个元素
    }
}

输出为

0   //输入
NOT FOUND
hello
the
world
{1=hello, 2=the, 3=world}
3
1
hello hello
the
world
{2=the, 3=world}
2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值