JavaSE 进阶 (6) 集合

泛型-概述

如果在创建集合的时候,不写泛型会怎么样?

/images/java/JavaSE 进阶 (6) 集合/1.png
(图1)
/images/java/JavaSE 进阶 (6) 集合/2.png
(图2)
/images/java/JavaSE 进阶 (6) 集合/3.png
(图3)

泛型概述

泛型:是 JDK5 中引入的特性,它提供了编译时类型安全检测机制

泛型的好处:

  • 把运行时期的问题提前到了编译期间
  • 避免了强制类型转换

Set-概述

集合类体系结构

/images/java/JavaSE 进阶 (6) 集合/4.png
(图4)

Set-基本使用

Set集合概述和特点

Set 集合的特点

  • 可以去除重复
  • 存取顺序 不一致
  • 没有带索引的方法,所以不能使用普通 for 循环遍历,也不能通过索引来获取/删除 set 集合里的元素

Set集合练习

存储字符串并遍历 (所有单列集合都可以使用迭代器进行遍历,所以 set 集合也可以使用)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MySet1 {
	public static void main(string[] args) {
		Set<String> set = new TreeSet();
		set.add("aaa");
		set.add("aaa");
		set.add("bbb");
		set.add("ccc");
	
		//for(int i = 0; i < set.size(); i++){
		//	//Set集合是没有索引的,所以不能使用通过索引获取元素的方法
		//}			
			

		Iterator<string> it = set.iterator();
		while(it.hasNext()){
			String s = it.next();
			System.out.println(s);  //aaa  bbb  ccc
		}
		//---------------------------------------------------
		for (String s : set){
			System.out.println(s);  //aaa  bbb  ccc
		}
	}
}

存储和取出的顺序不一致

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class MySet1 {
	public static void main(string[] args) {
		Set<String> set = new TreeSet();
		set.add("ccc");
		set.add("aaa");
		set.add("aaa");
		set.add("bbb");
		
		Iterator<string> it = set.iterator();
		while(it.hasNext()){
			String s = it.next();
			System.out.println(s);  //aaa  bbb  ccc
		}
		//---------------------------------------------------
		for (String s : set){
			System.out.println(s);  //aaa  bbb  ccc
		}
	}
}

TreeSet-基本使用

TreeSet集合概述和特点

TreeSet:底层是红黑树结构,所以要求元素必须排序


TreeSet 集合特点

  • 不包含重复元素的集合
  • 没有带索引的方法
  • 可以将元素按照规则进行排序 (TreeSet 虽然 不能保证存和取的顺序,但是可以 对内部的元素进行排序)

TreeSet 集合练习

  • 存储 Integer 类型的整数,并遍历
  • 存储学生对象,并遍历
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/**
 * Treeset集合来存储Integer类型
 */
public class MyTreeSet1 {
	public static void main(string[] args) {
		TreeSet<Integer> ts = new TreeSet<>();
		ts.add(5);
		ts.add(3);
		ts.add(4);
		ts.add(1);
		ts.add(2);
		System.out.println(ts);  //[1, 2, 3, 4, 5]
	}
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/**
 * Treeset集合来存储Student类型
*/
public class MyTreeset2 {
	public static void main(String[] args) {
		TreeSet<Student> ts = new TreeSet<>();
		Student s1 = new Student("小花"27);
		Student s2 = new Student("小花花"28);
		Student s3 = new Student("小小花"28);
		ts.add(s1);
		ts.add(s2);
		ts.add(s3);
		system.out.println(ts);
		//Exception in thread "main"java.lang.ClassCastException:class com.itheima.mytreeset.Student cannot be cast to class java.lan
		//报错的原因:没有指定排序的规则,是按照身高排,还是按照年龄排...,没有制定规则
	}
}

想要使用 TreeSet,需要制定排序规则


0%