java Collection和Map接口的区别

一、Collection接口
Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements)。一些Collection允许相同的元素而另一些不行。一些能排序而另一些不行。

JavaSDK不提供直接继承自Collection的类,Java SDK提供的类都是继承自Collection的“子接口”如List和Set。

Collection 接口的接口 对象的集合(单列集合)
├——-List 接口:元素按进入先后有序保存,可重复
│—————-├ LinkedList 接口实现类, 链表, 插入删除, 没有同步, 线程不安全
│—————-├ ArrayList 接口实现类, 数组, 随机访问, 没有同步, 线程不安全
│—————-└ Vector 接口实现类 数组, 同步, 线程安全
│ ———————-└ Stack 是Vector类的实现类
└——-Set 接口: 仅接收一次,不可重复,并做内部排序
├—————-└HashSet 使用hash表(数组)存储元素
│————————└ LinkedHashSet 链表维护元素的插入次序
└ —————-TreeSet 底层实现为二叉树,元素排好序
 

public class PracticeCollection {

    /**
	 * 向集合中插入重复的值
	 * @return
	 */
	public static ArrayList<String> makeList(){
		ArrayList<String> testList=new ArrayList<>();
		testList.add("tfq");
		testList.add("tfq");
		testList.add("tfq");
		testList.add("tfq1");
		testList.add("tfq1");
		return testList;
	}

	/**
	 * 不能存入重复的值到Set
	 * @return
	 */
	public static Set<String> makeSet(){
		Set<String> testList=new HashSet<>();
		testList.add("tfq");
		testList.add("tfq");
		testList.add("tfq");
		testList.add("tfq1");
		testList.add("tfq1");
		return testList;
	}


    public static void main(String[] args) {
		System.out.println("ArrayList打印:------>");
		makeList().stream().forEach(x->{
			System.out.println(x);
		});

		System.out.println("HashSet打印:------>");
		makeSet().stream().forEach(x->{
			System.out.println(x);
		});

	}

}
public class PracticMap {

	/**
	 * 接口实现类 ,没有同步, 线程不安全,通过Collections工具类解决集合类HashMap线程不安全问题
	 *
	 * @return
	 */
	public static Map<String, String> makeHashMap() {
		Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
		//模拟30个线程,往HashMap集合中添加数据
		for(int i = 1; i <= 30; i++) {
			new Thread(() -> {
				map.put(Thread.currentThread()
					.getName(), UUID.randomUUID()
					.toString()
					.substring(0, 8));
				System.out.println(map);
			}).start();
		}
		return map;
	}

	/**
	 * 通过JUC包下的并发集合类解决HashMap线程不安全问题,jdk1.8 API中的并发集合类截图如下
	 * @return
	 */
	public static Map<String, String> makeConcurrentHashMap() {
		Map<String, String> map =new ConcurrentHashMap<>();
		//模拟30个线程,往HashMap集合中添加数据
		for(int i = 1; i <= 30; i++) {
			new Thread(() -> {
				map.put(Thread.currentThread()
					.getName(), UUID.randomUUID()
					.toString()
					.substring(0, 8));
				System.out.println(map);
			}).start();
		}
		return map;
	}


	public static void main(String[] args) {
		makeConcurrentHashMap();
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值