Java集合(下)

目录

 

阐述

HashSet保证元素唯一性的原理

课后作业


阐述

HashSet保证元素唯一性的原理

HashSet在添加元素的过程中是通过遍历进行了数据的判断的。这个判断流程是:

首先比较对象的哈希值是否相同,这个哈希值是根据对象的hashCode()计算出来的;

如果哈希值不同,就直接添加到集合中;

如果哈希值相同,继续执行equals()进行比较,返回true说明元素重复,不添加,返回false说明元素不重复,就添加;

保存在HashSet中的对象要重写hashCode和equals方法,才能实现元素唯一性。现在的集成开发工具都可以自动生成这两个方法,不需要自己写。

课后作业

统计每个单词出现的次数
有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔)
打印格式:
    to=3
    think=1
    you=2
    ...

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

public class WordCount {
	public static void main(String[] args) {
		String sentence = "If you want to change your fate I think you must come to the dark horse to learn java";
		String[] wordArr = sentence.split(" ");
		Map<String, Integer> wordCount = new HashMap<String, Integer>();
		
		for(String word: wordArr) {
			wordCount.put(word, wordCount.containsKey(word) ? (wordCount.get(word) +1) : 1);
		}
		
		System.out.println("方法一:根据键找值-------------------------------------");
		for(String word: wordCount.keySet()) {
			System.out.println(word + "=" + wordCount.get(word));
		}
		
		System.out.println("方法二:根据键值对对象找键和值--------------------------");
		for(Map.Entry<String, Integer> entry: wordCount.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_40995238/article/details/112062753