黑马程序员——java基础——集合框架(二)

时间:2021-04-27 19:20:56

------- android培训java培训、期待与您交流! ----------

Set接口概述:

一个不包含重复元素的Collection。

Set代码案例:

public class SetDemo {
public static void main(String[] args) {
//創建集合對象
Set<String> set = new HashSet<String>();
//創建并天劍元素;
set.add("hello");
set.add("world");
set.add("java");
set.add("world");
//增強for
for(String s: set){
System.out.println(s);
}

HashSet案例:

Collection

  |--List

     有序(存储顺序和取出顺序一致),可重复

  |--Set

      无序(存储顺序和取出顺序不一致),唯一

HashSet:它不保证set 的迭代顺序;特别是它不保证该顺序恒久不变。

问题:?

为什么存储字符串的时候,字符串内容相同的只存储了一个呢?

哈希值是逻辑值;

地址值是物理值;

通过查看Add方法的源码,我们知道这个方法底层依赖两个方法:

HashCode()和 equals()。

If(e.hash == hash && ((k = e.key) ==key || key.equals((k)))

存储字符串并遍历:

public class HashSetDemo {
public static void main(String[] args) {
//創建集合對象
HashSet<String> hs = new HashSet<String>();
//創建并添加元素;
hs.add("hello");
hs.add("world");
hs.add("java");
//遍歷集合
for(String s : hs){
System.out.println(s);
}

存储自定义对象并遍历:

注意:因为HashSet底层依赖的是hashCode()和equals()方法。

而这两个方法如在该类中没有重写,所以,默认使用的是Object类。

这个时候,他们的哈希值是不会一样的,根本就不会继续判断,执行了添加操作。

LinkedHashSet概述:

LinkedHashSet : 底层数据结构有哈希表和链表组成。

哈希表保证元素的唯一性。

链表保证元素有序,(存储和取出时一致)。

TreeSet类概述:

使用元素的自然顺序对元素进行排序

或者根据创建Set时提供的Comparator进行排序具体取决于使用的构造方法。

A自然排序;

B 比较排序;

基于 TreeMapNavigableSet 实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的Comparator 进行排序,具体取决于使用的构造方法。

TreeSet()
构造一个新的空 set,该 set 根据其元素的自然顺序进行排序

TreeSet(Comparator<? super
E> comparator)

构造一个新的空 TreeSet,它根据指定比较器进行排序。

/*
* TreeSet:能夠對元素按照某種規則進行排序
* 排序有兩種方式:
* A:自然排序
* B:比較排序
*
*/
public class TreeSetDemo {

public static void main(String[] args) {
// TODOAuto-generated method stub
//創建集合對象
//自然排序
TreeSet<Integer> ts = new TreeSet<Integer>();
//創建并添加元素
ts.add(25);
ts.add(23);
ts.add(33);
ts.add(33);
ts.add(34);
ts.add(36);
ts.add(40);
//遍歷
for(Integer i : ts){
System.out.println(i);
}
}

元素是如何取出来的呢?(前序遍历,中序遍历,后序遍历)

  从根节点开始,按照左,中,右的原则依次取出元素即可。

以上的代码由于实现了Integer和String的Comparable接口;

TreeSet存储自定义对象并保证元素排序和唯一。

Treeset集合保证元素排序和唯一性的原理:

排序:

A:自然排序(元素具备比较性):

   让元素所属的类实现自然排序接口Comparable;

B:比较器排序(集合具备比较性):

   让集合的构造方法接收一个比较器接口的子类对象Comparator;

Student类实现的comparable<T>接口的compareTo方法;

ClassCastException

要有排序的规则;

1.自然排序;

如按照姓名长度排序:

 1.长度,姓名内容是否相同, 年龄;

public int compareTo(Student s) {
// TODOAuto-generated method stub
//return 0;
//这里返回什么,其实应该根据我的排序规则来做。
//按照年龄排序;主要条件
int num =this.age - s.age;
//次要条件
//年龄相同的时候,还得去看姓名是否也相同
//如果年龄和姓名都相同,才是同一个元素;
int num2 = num==0?this.name.compareTo(s.name):num;
return num2;
}

/*
* TreeSet存储自定义对象并保证排序唯一。
*
*/
public class TreeSetDemo2 {
/*TreeSet存储自定义对象并保证元素排序和唯一:
* A:你没有告诉我怎么排序
* 自然排序;按照年龄从小到大排序;
* B:元素什么情况唯一。
* 成员变量值都相同为同一个元素;
*
*/

public static void main(String[] args) {
// TODOAuto-generated method stub
TreeSet<Student> ts =new TreeSet<Student>();
//创建元素
Student s1= new Student("lingqingxia" , 25);
Student s2= new Student("gongjiao", 26);
Student s3 = new Student("simin", 22);
Student s4 = new Student("tangqilan", 28);
//添加元素
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);

//遍历:
for(Student s: ts){
System.out.println(s.getName()+"----------"+s.getAge());
}

}
}

2.比较排序:

TreeSet(Comparator<? superE> comparator)

通过实现该接口的子类对象,创建外部类;

如果一个方式的参数是接口,那么真正要的是接口的实现类对象;

而匿名内部类就可以实现这个东西;

//public  TreeSet (TreeSet(Comparator<? super E>comparator)  comparator)//比较器排序;
//TreeSet<Student> ts= new TreeSet<Student>(new MyComparator());
//如果一个方法的参数是接口,那么真正要的是接口的实现类的对象;
//而匿名内部类就可以实现这个东西;
TreeSet<Student> ts = new TreeSet<Student>(newComparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
//姓名长度;
int num = o1.getName().length() -o2.getName().length();
//姓名内容;
int num2 = num ==0 ?o1.getName().compareTo(o2.getName()):num;
int num3 = num2 ==0 ? o1.getAge() -o2.getAge():num2;

return num3;
}

Map集合

public interface Map<K,V>

K -此映射所维护的键的类型

V  -映射值得类型

将键映射到的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。

1.Map集合的特点:

通过查看API,我们知道Map集合的一个最大的特点,就是它可以存储键值对的元素。

2.Map集合和Collection集合的区别:

   Map集合存储元素是成出现的,Map集合的键是唯一的,值是可重复的。

   Collection集合存储元素是单独出现的,Collection的Set是唯一的,List是可重复的。

Map集合的数据结构值针对键有效,跟值无关

Collection集合的数据结构是针对元素有效的

Map集合的功能概述:

1.      添加功能:

V  put(K  key ,V value):添加元素,返回元素;两种功能;

 如果键是第一次存储,就直接存储元素,返回null

 如果不是第一次存在,就用值把以前的值替换掉,返回以前的值

   2.删除功能:

     Void  clear( ) :移除所有的键值对元素

     V  remove(Object key): 根据键删除键值对元素,并把值返回

3.判断功能:

 Boolean containsKey(Object  key):判断集合是否包含指定的键

 Boolean containsValue(Object  value):判断集合是否包含指定的值

 Boolean  isEmpty():判断集合是否为空

4.获取功能:

   Set<Map.Entry<K,V>>  entrySet():返回的是键值对对象的集合;

   V  get(Object key):根据键获取值

Set<K>  keySet():获取集合中所有键的集合

Collection<V>  values():获取集合中所有值得集合。

5.长度功能:

   Int size():返回集合中的键值对的对数;

获取功能:

//创建集合对象;
Map<String, String> map = new HashMap<String,String>();
//添加元素;
map.put("邓超", "孙俪");
map.put("黄晓明", "angelbably");
map.put("周杰伦", "昆凌");
map.put("刘恺威", "杨幂");
//V get(Object key):根据键获取值
System.out.println("get:"+map.get("周杰伦"));
System.out.println("map"+map);
System.out.println("--------------");
//Set<k> keySet():获取集合中所有键的集合
Set<String> set =map.keySet();
for(String key : set){
System.out.println(key);
}
//Collection<V> values():获取集合中所有值得集合
Collection<String> con = map.values();
for(String value : con){
System.out.println(value);
}

}

Map集合的遍历:

1.      map集合的遍历之键找值;

方式1:根据键找值;

  获取所有键的集合

  遍历键的集合,获取到每一个键

  根据键找值

   //创建集合对象
Map<String ,String>map = new HashMap<String ,String>();
//创建元素并添加到结合;
map.put("西门庆", "潘金莲");
map.put("杨过", "小龙女");
map.put("郭靖", "黄蓉");
map.put("宋江", "刘诗诗");

//遍历
//获取所有的键
Set<String> set = map.keySet();
//遍历键的集合,获取得到每一个键
for(String key : set){
//根据键去找值;
String value = map.get(key);
System.out.println(key+"-----"+ value);
}

2.   Map集合的遍历之键值对对象找键和值;

 方式2:根据键值对对象找键和值

 获取所有键值对对象的集合

 遍历键值对对象的集合,获取到每一个键值对象

 根据键值对对象找键和值

 /*
* map集合的遍历:
* Map --夫妻对
* 思路:
* A:获取所有结婚证的集合
* B:遍历结婚证的集合,得到每一个结婚证
* C:根据结婚证获取丈夫和妻子
*
* 转换:
* A:获取所有键值对对象的集合;
* B:遍历键值对对象的集合,得到每一个键值对对象
* c:根据键值对对象获取键和值
* 键值对对象如何表示:
* Set<Map.Entry<K ,V>> entrySet():返回的是键值对对象的集合;
*/

public class MapDemo4 {
public static void main(String[] args) {
//创建集合对象
Map<String ,String>map = new HashMap<String ,String>();
//创建元素并添加到结合;
map.put("西门庆", "潘金莲");
map.put("杨过", "小龙女");
map.put("郭靖", "黄蓉");
map.put("宋江", "刘诗诗");
//获取所有键值对对象的集合;
Set<Map.Entry<String ,String>> set= map.entrySet();
for(Map.Entry<String ,String> me : set){
//根据键值对对象获取键和值
String key = me.getKey();
String value = me.getValue();
System.out.println(key + "------"+ value);
}
}
}

HashMap

HashMap:是基于哈希表的Map接口实现。

哈希表的作用是用来保证键的唯一性。

HashMap<String , String>

HashMap<Integer ,String>

HashMap<String ,String>

HashMap<Student String>

1.hashMap集合键是String值String的案例;

public class HashMapDemo {
public static void main(String[] args) {
//创建集合对象
HashMap<String ,String> hm = new HashMap<String, String>();
//创建元素并添加元素
hm.put("it001", "马云");
hm.put("it002", "马化腾");
hm.put("it003", "乔布斯");
hm.put("it004", "张朝阳");
hm.put("it005", "裘伯君");
String s= hm.put("it001", "比尔");
System.out.println(s);
System.out.println("----------");
//遍历
Set<String> set = hm.keySet();
for(String key : set){
String value = hm.get(key);
System.out.println(key + "-----"+ value);
}
}
}

2.HashMap集合键是Integer值是String的案例;

/*
* HashMap<Integer,String>
*/
public class HashMapDemo2 {
public static void main(String[] args) {
//创建集合对象
HashMap<Integer ,String> hm = new HashMap<Integer,String>();

//创建元素并添加元素
// Integer i = new Integer(100);
Integer i = 27;
String S ="刘亦菲";

hm.put(25, "刘洋");
hm.put(21,"刘明宇");
hm.put(24, "肖旭");
hm.put(23,"黎小龙");
hm.put(22, "刘洋");
//下面的写法是八进制,但是不能出现8以上的耽搁数据
hm.put(025, "hello");
hm.put(007, "hello");
// hm.put(008, "hello");
//遍历
Set<Integer> set = hm.keySet();
for(Integer key : set){
Stringvalue = hm.get(key);
System.out.println(key+"------"+ value);
}
}
}

4.HashMap集合键是String值是Student的案例:

public class HashMapDemo3 {
public static void main(String[] args) {
// 创建集合对象
HashMap<String, Student> hm = new HashMap<String, Student>();
// 创建学生对象
Student s1 = new Student("周星驰", 58);
Student s2 = new Student("刘德华", 55);
Student s3 = new Student("梁朝伟", 54);
Student s4 = new Student("刘嘉玲", 50);

// 添加元素
hm.put("9527", s1);
hm.put("9522", s2);
hm.put("9524", s3);
hm.put("9529", s4);

// 遍历
Set<String> set = hm.keySet();
for (String key : set) {
// 注意了:这次值不是字符串了
// String value = hm.get(key);
Student value = hm.get(key);
System.out.println(key + "---" + value.getName() + "---"
+ value.getAge());
}
}
}

5.HashMap集合键是Student值是String的案例:

Student类要重写hashCode()和equals()方法;

*HashMap<Student,String>
* 键:Student
* 要求:如果两个对象的成员变量值都相同,则为同一个对象。
* 值:String
*/
public class HashMapDemo4 {
public static void main(String[] args) {
// 创建集合对象
HashMap<Student, String> hm = new HashMap<Student, String>();

// 创建学生对象
Student s1 = new Student("貂蝉", 27);
Student s2 = new Student("王昭君", 30);
Student s3 = new Student("西施", 33);
Student s4 = new Student("杨玉环", 35);
Student s5 = new Student("貂蝉", 27);

// 添加元素
hm.put(s1, "8888");
hm.put(s2, "6666");
hm.put(s3, "5555");
hm.put(s4, "7777");
hm.put(s5, "9999");

// 遍历
Set<Student> set = hm.keySet();
for (Student key : set) {
String value = hm.get(key);
System.out.println(key.getName() + "---" + key.getAge() + "---"
+ value);
}
}
}

LinkedHashMap的概述和使用;

Map接口的哈希表和链接列表实现,具有可预知的迭代顺序。

由哈希表保证键的唯一性;

由链表保证键盘的有序(存储和取出的顺序一致)

TreeMap集合键是String值是String的案例

键是红黑树结构,可以保证键的排序和唯一性

TreeMap案例:

TreeMap<String, String>

//创建集合对象
TreeMap<String,String> tm = new TreeMap<String, String>();

//创建元素并添加元素
tm.put("hello","你好");
tm.put("world","世界");
tm.put("java","22刘洋");
tm.put("world","25刘明宇");
tm.put("javaee","24");
//遍历集合
Set<String> set = tm.keySet();
for(String key : set){
String value = tm.get(key);
System.out.println(key+"-----"+value);
}

TreeMap<Student,String>

 //创建集合对象
TreeMap<Student ,String> tm=new TreeMap<Student,String>(new Comparator<Student>(){

@Override
public int compare(Student s1, Student s2) {
// TODOAuto-generated method stub
int num = s1.getAge() - s2.getAge();
int num2= num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
//创建学生对象
Student s1 = new Student("潘安",30);
Student s2 = new Student("柳下惠",35);
Student s3 = new Student("唐伯虎",33);
Student s4 = new Student("燕青", 28);
Student s5 = new Student("柳下惠",35);
//存储元素;
tm.put(s1, "1230");
tm.put(s2, "宋朝");
tm.put(s3, "明朝");
tm.put(s4, "宋朝");
tm.put(s5, "3456");
//遍历元素
Set<Student> set = tm.keySet();
for(Student key : set){
String value = tm.get(key);
System.out.println(key.getName()+"----"+ key.getAge()+
"-----"+ value);
}

集合的嵌套遍历:

1.HashMap 嵌套HashMap

/*
* HashMap嵌套HashMap
*
* 传智播客
* jc 基础班
* 陈玉楼 20
* 高跃 22
* jy 就业班
* 李杰 21
* 曹石磊 23
*
* 先存储元素,然后遍历元素
*/
public class HashMapDemo2 {
public static void main(String[] args) {
// 创建集合对象
HashMap<String, HashMap<String,Integer>> czbkMap = newHashMap<String, HashMap<String, Integer>>();

// 创建基础班集合对象
HashMap<String, Integer> jcMap = new HashMap<String, Integer>();
// 添加元素
jcMap.put("陈玉楼", 20);
jcMap.put("高跃", 22);
// 把基础班添加到大集合
czbkMap.put("jc", jcMap);

// 创建就业班集合对象
HashMap<String, Integer> jyMap = new HashMap<String, Integer>();
// 添加元素
jyMap.put("李杰", 21);
jyMap.put("曹石磊", 23);
// 把基础班添加到大集合
czbkMap.put("jy", jyMap);

//遍历集合
Set<String> czbkMapSet =czbkMap.keySet();
for(String czbkMapKey : czbkMapSet){
System.out.println(czbkMapKey);
HashMap<String, Integer>czbkMapValue = czbkMap.get(czbkMapKey);
Set<String> czbkMapValueSet =czbkMapValue.keySet();
for(String czbkMapValueKey : czbkMapValueSet){
Integer czbkMapValueValue =czbkMapValue.get(czbkMapValueKey);
System.out.println("\t"+czbkMapValueKey+"---"+czbkMapValueValue);
}
}
}
}

2.HashMap 嵌套ArrayList

/*
*需求:
*假设HashMap集合的元素是ArrayList。有3个。
*每一个ArrayList集合的值是字符串。
*元素我已经完成,请遍历。
*结果:
* 三国演义
* 吕布
* 周瑜
* 笑傲江湖
* 令狐冲
* 林平之
* 神雕侠侣
* 郭靖
* 杨过
*/
public class HashMapIncludeArrayListDemo {
public static void main(String[] args) {
// 创建集合对象
HashMap<String,ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

// 创建元素集合1
ArrayList<String> array1 = new ArrayList<String>();
array1.add("吕布");
array1.add("周瑜");
hm.put("三国演义", array1);

// 创建元素集合2
ArrayList<String> array2 = new ArrayList<String>();
array2.add("令狐冲");
array2.add("林平之");
hm.put("笑傲江湖", array2);

// 创建元素集合3
ArrayList<String> array3 = new ArrayList<String>();
array3.add("郭靖");
array3.add("杨过");
hm.put("神雕侠侣", array3);

//遍历集合
Set<String> set = hm.keySet();
for(String key : set){
System.out.println(key);
ArrayList<String> value =hm.get(key);
for(String s : value){
System.out.println("\t"+s);
}
}
}
}

3.ArrayList 嵌套 HashMap

/*
ArrayList集合嵌套HashMap集合并遍历。
需求:
假设ArrayList集合的元素是HashMap。有3个。
每一个HashMap集合的键和值都是字符串。
元素我已经完成,请遍历。
结果:
周瑜---小乔
吕布---貂蝉

郭靖---黄蓉
杨过---小龙女

令狐冲---任盈盈
林平之---岳灵珊
*/
public class ArrayListIncludeHashMapDemo {
public static void main(String[] args) {
// 创建集合对象
ArrayList<HashMap<String,String>> array = newArrayList<HashMap<String, String>>();

// 创建元素1
HashMap<String, String> hm1 = new HashMap<String, String>();
hm1.put("周瑜", "小乔");
hm1.put("吕布", "貂蝉");
// 把元素添加到array里面
array.add(hm1);

// 创建元素1
HashMap<String, String> hm2 = new HashMap<String, String>();
hm2.put("郭靖", "黄蓉");
hm2.put("杨过", "小龙女");
// 把元素添加到array里面
array.add(hm2);

// 创建元素1
HashMap<String, String> hm3 = new HashMap<String, String>();
hm3.put("令狐冲", "任盈盈");
hm3.put("林平之", "岳灵珊");
// 把元素添加到array里面
array.add(hm3);

// 遍历
for (HashMap<String, String> hm : array) {
Set<String> set = hm.keySet();
for (String key : set) {
String value = hm.get(key);
System.out.println(key + "---" + value);
}
}
}
}

Hashtable 和hashMap的区别:

HashMap:线层不安全,效率高。允许null键和null值;

Hashtable:线程安全,效率低。不允许null键和null值;

List,Set,Map等接口是否都继承Map接口:

List , Set不是继承自Map接口,它们继承Collection接口;

Map接口本身就是一个顶层接口;

Collection类概述:

针对集合操作的工具类,都是静态方法;

Collection和Collections的区别?

Collection:是单列集合的顶层接口,有子接口List和Set。

Collections:是针对集合操作的工具类,有对集合进行排序和二分查找的方法。

 

Collection主要方法:

Public static <T> void sort(List<T> list):排序默认情况下是自然排序。

Public static <T> int binarySearch(List<?> list , T key):二分查找

Public static<T> T max(Collection<?>  coll):最大值

Public static  void  reverse(List<?>  list):反转

Public static  void  shuffle(List<?>  list):随机置换