集合
1.什么是集合?
集合是java中提供的一种容器,可以用来存储多个数据
集合和数组的区别
2.Collection父接口
2.1.特点:代表一组任意类型的对象,无序、无下标、不能重复
2.2.创建集合 :
Collection collection = new ArrayList();
2.3.常用方法
-
添加元素 : collection.add();
-
**删除元素 **: collection.remove(); collection.clear();
-
遍历元素(重点):
-
使用增强for(因为无下标)
for(Object object : collection){ }
-
使用迭代器
-
-
判断: collection.contains(); collection.isEmpty();
public class collection { public static void main(String[] args) { //创建接口 Collection collection = new ArrayList(); //添加元素 collection.add("番茄"); collection.add("西红柿"); collection.add("西瓜"); System.out.println("元素个数:"+collection.size());//3 System.out.println(collection); //删除元素 //collection.remove("西红柿"); //collection.clear();//删除全部 //System.out.println("删除后:"+collection.size());//2 //System.out.println(collection); System.out.println("=================="); //遍历元素 //使用增强for for (Object obj : collection){ System.out.println(obj); } //使用迭代器(迭代器专门用来遍历集合的一种方式) //haNext(); 有没有下一个元素 //next(); 获取下一个元素 //remove(); 删除当前元素 System.out.println("===================="); Iterator it = collection.iterator(); while (it.hasNext()){ String s = (String) it.next(); System.out.println(s); //不能使用collection //collection.remove(s); // it.remove(); } System.out.println("元素个数为:"+collection.size()); //判断 System.out.println(collection.contains("番茄")); System.out.println(collection.isEmpty());//判断是否为空 } }
package Demo25; import Demo21.Person; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * @author fanqie * @date 2021/3/20 -15:45 * collection接口的使用 * 1.添加元素 * 2.删除元素 * 3.遍历元素 * 4.判断 */ public class collection2 { public static void main(String[] args) { Collection collection = new ArrayList(); Student student = new Student("番茄",17); Student student1 = new Student("张三",15); Student student2 = new Student("西红柿",12); collection.add(student); collection.add(student1); collection.add(student2); System.out.println("元素个数为:"+collection.size()); System.out.println(collection.toString()); System.out.println("==========================删除================="); collection.remove(student); System.out.println("删除之后:"+collection); //collection.clear();//清空全部 System.out.println("==========增强for==============="); for (Object obj : collection) { Student s = (Student)obj; System.out.println(obj); } System.out.println("==============迭代器======================="); Iterator it = collection.iterator(); while (it.hasNext()){ Student s2 = (Student) it.next(); System.out.println(s2.toString()); } //判断 System.out.println(collection.contains(student2)); System.out.println(collection.isEmpty());//判断是否为空 } }
3.List集合:
特点:
有序(元素的存取顺序一致),可重复
注意:
list是接口,所以可以通过创建其子类ArrayList对象来完成该接口的实例化
List list = new ArrayList();
常用方法:
-
添加元素
list.add( );
会对基本类型进行自动装箱 -
删除元素 可以用索引
list.remove(0)
当删除数字与索引矛盾时 对数字强转
list.remove((Object) 10)
或
list.remove(new Integer(10)) -
遍历
-
使用for遍历
//使用for循环遍历 System.out.println("===================使用for循环遍历==================="); for (int i = 0; i <list.size() ; i++) { Student student = (Student) list.get(i); System.out.println(i+":"+student); }
-
使用增强for
for (Object object : list) { Student student2 = (Student) object; System.out.println(student2); }
-
使用迭代器
Iterator it = list.iterator(); while (it.hasNext()){ Student student3 = (Student) it.next(); System.out.println(student3); }
-
使用列表迭代器 💡(注意和迭代器区别)
System.out.println("===================使用列表迭代器从前往后遍历==================="); ListIterator lit = list.listIterator(); while (lit.hasNext()){ System.out.println(lit.nextIndex()+":"+lit.next()); } System.out.println("===================使用列表迭代器从后往前遍历==================="); while (lit.hasPrevious()){ System.out.println(lit.previousIndex()+":"+lit.previous()); }
-
-
获取
list.indexOf( );
-
返回子集合
sublist(x, y);
左闭右开List subList = list.subList(1, 3);
返回索引 1、2
List实现类
-
ArrayList 【重点】
- 数组结构实现,必须要连续空间,查询快、增删慢
- jdk1.2版本,运行效率块、线程不安全
-
Vector
- 数组结构实现,查询快、增删慢
- jdk1.0版本,运行
-
LinkedList
- 双向链表结构实现,无需连续空间,增删快,查询慢
使用集合的步骤:
-
创建元素对象
-
创建元素对象
-
将元素对象添加到集合对象中
-
遍历集合
实例:
public class list {
public static void main(String[] args) {
//创建集合对象
List list = new ArrayList();
//创建元素对象
Student s = new Student("番茄",17);
Student s1 = new Student("李四",17);
Student s2 = new Student("王五",19);
Student s3 = new Student("嘟嘟嘟",14);
//将元素对象添加到集合对象中
list.add(s);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("元素个数:"+list.size());//打印元素个数:4
System.out.println(list.toString());//打印属性
//删除元素
//list.remove("王五");
//list.remove(2);
//System.out.println("删除后的元素个数:"+list.size());
//System.out.println(list.toString());
//遍历
//使用for循环遍历
System.out.println("===================使用for循环遍历===================");
for (int i = 0; i <list.size() ; i++) {
Student student = (Student) list.get(i);
System.out.println(i+":"+student);
}
//使用增强for循环遍历
System.out.println("===================使用增强for循环遍历===================");
for (Object object : list) {
Student student2 = (Student) object;
System.out.println(student2);
}
//使用迭代器遍历
System.out.println("===================使用迭代器遍历===================");
Iterator it = list.iterator();
while (it.hasNext()){
Student student3 = (Student) it.next();
System.out.println(student3);
}
//使用列表迭代器遍历,和Iterator的区别,ListIterator可以向前或向后遍历,添加、删除、修改元素
System.out.println("===================使用列表迭代器从前往后遍历===================");
ListIterator lit = list.listIterator();
while (lit.hasNext()){
System.out.println(lit.nextIndex()+":"+lit.next());
}
//使用列表迭代器遍历,和Iterator的区别,ListIterator可以向前或向后遍历,添加、删除、修改元素
System.out.println("===================使用列表迭代器从后往前遍历===================");
while (lit.hasPrevious()){
System.out.println(lit.previousIndex()+":"+lit.previous());
}
//判断
System.out.println(list.contains("番茄"));//判断
System.out.println(list.isEmpty()); //判断是否为空
//获取位置
System.out.println(list.indexOf("番茄"));
}
public class list02 {
public static void main(String[] args) {
//创建集合对象
List list = new ArrayList();
//添加数字数据(自动装箱)
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.add(60);
System.out.println("元素个数:"+list.size());
System.out.println(list.toString());
//删除元素
//list.remove(0);//数组下标删除
//list.remove((Object) 20);
list.remove(new Integer(20));
System.out.println("删除后的元素个数:"+list.size());
System.out.println(list.toString());
//3.补充方法sublist ,返回子集合,含头不含尾
List sub = list.subList(1,3);
System.out.println(sub.toString());
}
}
4.ArrayList集合:
特点:
1.数组结构实现,查询快、增删慢
2.jdk 1.2版本,运行效率快、线程不安全
创建集合 ArrayList arrayList = new ArrayList<>();
public boolean equals(Object obj){
//1 判断是不是同一个对象
if(this == obj){
return true;
}
//2 判断是否为空
if(obj == null){
return false;
}
//3 判断是否是Student类型
if(obj instanceof Student){
Student == (Student)obj;
//4 比较属性
if(this.name.equals(s.getName()) && this.age == s.getAge()){
return true;
}
}
//5 不满足条件返回false
return false;
}
3.遍历元素【重点】
-
使用迭代器
Iterator it = arrayList.iterator(); while(it.hasNext()){ Student s = (Student)it.next(); //强转 }
-
列表迭代器
ListIterator li = arrayList.listIterator(); while(li.hasNext()){ Student s = (Student)li.next(); //从前往后遍历 } while(li.hasPrevious()){ Student s = (Student)li.previous();//从后往前遍历 }
4.判断
arrayList.contains(); 和 arrayList.isEmpty();
5.查找
arrayList.indexof();
原码分析
DEFAULT_CAPACITY = 10; //默认容量
//注意:如果没有向集合中添加任何元素时,容量0,添加一个后,容量为10
//每次扩容是原来的1.5倍
elementData存放元素的数组
size 实际元素个数
实例:
//1. 创建集合对象
List list = new ArrayList();
//2. 创建元素对象
Student student = new Student("番茄",17);
Student student1 = new Student("柿子",17);
Student student2 = new Student("西红柿",17);
Student student3 = new Student("番茄",17);
//3. 将元素对象添加到集合对象中
list.add(student);
list.add(student1);
list.add(student2);
list.add(student3);
//直接打印
System.out.println(list);
//获取索引为2的元素
Object obj = list.get(2);
System.out.println(obj);
//获取集合的元素长度
list.size();//4
//4. 遍历集合
for (int i = 0; i <list.size() ; i++) {
Object obj2 = list.get(i);
System.out.println("索引为:"+i+"的属性值:"+obj2);
}
System.out.println("------------------------");
//5. 通过增强for遍历list集合
for (Object obj3 : list){
//Object是集合中的元素,其本身应该是Integer类型的数据
System.out.println(obj3);
}
}
}
5.Vector集合
1.特点:
1.数组结构实现,查询快、增删慢
2.jdk 1.0版本,运行效率慢、线程安全
创建集合 Vector vector = new Vector<>();
增加、删除、判断同上
遍历中枚举器遍历
Enumeration elements = vector.elements();
while (elements.hasMoreElements()){
String s = (String) elements.nextElement();
System.out.println(s.toString());
}
2.实例:
public class vector {
public static void main(String[] args) {
//1.创建集合
Vector vector = new Vector();
//2.添加元素
vector.add("西瓜");
vector.add("番茄");
vector.add("西红柿");
vector.add("胡萝卜");
System.out.println(vector.toString());
//3.删除
//vector.remove(0);
//vector.remove("西瓜");
//vector.clear();
System.out.println("被删除后:"+vector.toString());
//4.遍历
//使用枚举器
Enumeration elements = vector.elements();
while (elements.hasMoreElements()){
String s = (String) elements.nextElement();
System.out.println(s.toString());
}
//5.判断
System.out.println(vector.contains("西瓜"));
System.out.println(vector.isEmpty());
}
}
6.LinkedList
1.特点:
链表结构实现,增删快,查询慢。
创建链表集合LinkedList li = new LinkedList<>();
常用方法与List一致
2.实例:
public class linkedList {
public static void main(String[] args) {
//1.创建结合
LinkedList linkedList = new LinkedList();
//2.添加元素
Student s = new Student("番茄",17);
Student s1 = new Student("李四",17);
Student s2 = new Student("王五",19);
Student s3 = new Student("嘟嘟嘟",14);
linkedList.add(s);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
System.out.println("元素个数:"+linkedList.size());
System.out.println(linkedList.toString());
//3.删除
//linkedList.remove(s);
//linkedList.remove(0);
//linkedList.remove( new Student("番茄",17));
System.out.println("删除之后元素个数:"+linkedList.size());
System.out.println(linkedList.toString());
//4.遍历
//4.1.for遍历
System.out.println("-------------------for遍历-------------------");
for (int i = 0; i <linkedList.size() ; i++) {
Student student = (Student) linkedList.get(i);
System.out.println(student.toString());
}
//4.2.增强for遍历
System.out.println("-------------------增强for遍历-------------------");
for (Object o : linkedList) {
Student student =(Student) o;
System.out.println(student.toString());
}
//4.3.迭代器遍历
System.out.println("-------------------迭代器遍历-------------------");
Iterator it = linkedList.iterator();
while (it.hasNext()){
Student student = (Student) it.next();
System.out.println(student.toString());
}
//4.3.列表迭代器遍历
System.out.println("-------------------列表迭代器遍历-------------------");
ListIterator listIterator = linkedList.listIterator();
while (listIterator.hasNext()){
Student student = (Student) listIterator.next();
System.out.println(student.toString());
}
//4.4.逆序迭代器遍历
System.out.println("-------------------逆序迭代器遍历-------------------");
while (listIterator.hasPrevious()){
Student student = (Student) listIterator.previous();
System.out.println(student.toString());
}
//5.判断
System.out.println(linkedList.contains(0));
System.out.println(linkedList.isEmpty());
//获取元素下标位置
System.out.println(linkedList.indexOf(s2));
}
}
7.泛型
- 本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类、泛型接口、泛型方法
- 语法 T成为类型占位符,表示一种引用类型,可以写多个逗号隔开
- 好处 1. 提高代码重用性 2. 防止类型转换异常,提高代码安全性
package Demo25;
/**
* @author fanqie
* @date 2021/3/25 -13:57
* 泛型类
* 语法:类名<T>
* T是类型站位符,表示一种引用类型,如果编写多个使用逗号隔开
*/
public class MyGeneric<T> {
//使用泛型<T>
//1.创建泛型
T t;
//2.泛型作为方法的参数
public void show(T t){
System.out.println(t);
}
//3.泛型作为方法的返回值
public T getT(){
return t;
}
}
package Demo25;
/**
* @author fanqie
* @date 2021/3/25 -14:02
* 泛型的实现
*/
public class TestGeneric {
public static void main(String[] args) {
//使用泛型类创建对象
//注意:1.泛型只能使用引用类型 2.不同泛型类型对象之间不能相互赋值
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t="hello";
myGeneric.show("大家好,加油");
String t = myGeneric.getT();
System.out.println(t);//hello
MyGeneric<Integer> myGeneric1 = new MyGeneric<Integer>();
myGeneric1.t=20;
myGeneric1.show(200);
Integer t1 = myGeneric1.getT();
System.out.println(t1);//20
}
}
泛型接口
语法:接口名
注意:不能泛型静态常量
package Demo25;
/**
* @author fanqie
* @date 2021/3/25 -14:11
* 泛型接口
* 注意:不能泛型静态常量
* 语法:接口名:<T>
*/
public interface MyInterface<T> {
String name = "张三";
T server(T t);
}
package Demo25;
/**
* @author fanqie
* @date 2021/3/25 -14:11
* 泛型接口实现类
*/
public class MyInterfaceImpl implements MyInterface<String>{
@Override
public String server(String s) {
System.out.println(s);
System.out.println("卢本伟牛逼");
return s;
}
}
System.out.println("============泛型接口的实现=====================");
MyInterfaceImpl myInterface = new MyInterfaceImpl();
myInterface.server("aaaa");
package Demo25;
/**
* @author fanqie
* @date 2021/3/25 -14:11
* 泛型接口实现类
*/
public class MyInterfaceImpl2<T> implements MyInterface<T>{
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
MyInterfaceImpl2<Integer> myInterfaceImpl2 = new MyInterfaceImpl2<>();
myInterfaceImpl2.server(1000);
泛型方法
语法: 返回值类型
public class MyGenericMethod {
//泛型方法
public <T> T show(T t){
System.out.println("泛型方法:"+t);
return t;
}
}
System.out.println("============泛型方法的实现=====================");
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show("番茄");// 自动类型为字符串
myGenericMethod.show(200);// integer类型
myGenericMethod.show(3.14);// double类型
泛型集合
**概念:**参数化类型、类型安全的集合,强制集合元素的类型必须一致
特点:
-
编译时即可检查,而非运行时抛出异常
-
访问时,不必类型转换(拆箱)
-
不同泛型之间应用不能相互赋值,泛型不存在多态
8.Set集合
**特点:**无序、无下标、元素不可重复
**方法:**全部继承自Collection中的方法
增、删、遍历、判断与collection一致
9.HashSet[重点]
**存储结构:**哈希表(数组+链表+红黑树)
存储过程(重复依据)
-
根据hashCode计算保存的位置,如果位置为空,直接保存,若不为空,进行第二步
-
再执行equals方法,如果equals为true,则认为是重复,否则形成链表
特点
-
基于HashCode计算元素存放位置
-
利用31这个质数,减少散列冲突
- 31提高执行效率
31 * i = (i << 5) - i
转为移位操作
- 31提高执行效率
-
当存入元素的哈希码相同时,会调用equals进行确认,如果结果为true,则拒绝后者存入
-
语法:
新建集合: HashSet<String> hashSet = new HashSet<String>();
添加元素: hashSet.add( );
删除元素: hashSet.remove( );
遍历操作:
1. 增强for for( type type : hashSet)
2. 迭代器 Iterator<String> it = hashSet.iterator( );
判断 hashSet.contains( );
hashSet.isEmpty();
package Demo25;
import java.util.HashSet;
import java.util.Iterator;
/**
* @author fanqie
* @date 2021/3/25 -15:03
* HashSet集合的使用
* 储存结构:哈希表(数组+链表+红黑树)
*
*/
public class hash_Set {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<>();
hashSet.add("番茄");
hashSet.add("西红柿");
hashSet.add("茄子");
hashSet.add("的");
System.out.println("元素个数:"+hashSet.size());
System.out.println(hashSet.toString());
hashSet.remove("的");
System.out.println("删除后元素个数:"+hashSet.size());
System.out.println("删除后:"+hashSet.toString());
System.out.println("===============增强for遍历=============");
for (String s : hashSet) {
System.out.println(s);
}
System.out.println("===================迭代器===================");
Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("==================判断===============");
System.out.println(hashSet.contains("硅谷"));
System.out.println(hashSet.isEmpty());
}
}
package Demo25;
import java.util.HashSet;
import java.util.Iterator;
/**
* @author fanqie
* @date 2021/3/25 -15:03
* HashSet集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
* 存储过程:
* 1.根据hashCode计算保存的位置,如果位置为空,直接保存,若不为空,进行第二步
* 2.再执行equals方法,如果equals为true,则认为是重复,否则形成链表
*
*/
public class hash_Set02 {
public static void main(String[] args) {
//1.创建集合
HashSet<Student> hashSet = new HashSet<>();
//2.添加数据
Student student = new Student("番茄",10);
Student student1 = new Student("西红柿",10);
Student student2 = new Student("茄子",10);
Student student3 = new Student("的",10);
hashSet.add(student);
hashSet.add(student1);
hashSet.add(student2);
hashSet.add(student3);
System.out.println("元素个数:"+hashSet.size());
System.out.println(hashSet.toString());
//3.删除
// hashSet.remove(new Student("的",10));//因为重写了equals方法,可以删除
hashSet.remove(student3);
System.out.println("删除后的元素个数:"+hashSet.size());
System.out.println("删除后:"+hashSet.toString());
//4.遍历[重点]
//4.1.增强for循环遍历
System.out.println("===============增强for循环遍历==============");
for (Student student4 : hashSet) {
System.out.println(student4.toString());
}
//4.2.迭代器遍历
System.out.println("===============迭代器遍历==============");
Iterator<Student> iterator = hashSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//5.判断
System.out.println(hashSet.contains(student));
System.out.println(hashSet.isEmpty());
}
}
10.TreeSet
特点
-
基于排列顺序实现元素不重复
-
实现SortedSet接口,对集合元素自动排序
-
元素对象的类型必须实现Comparable接口,指定排序规则
-
通过CompareTo方法确定是否为重复元素
存储结构:红黑树
方法:
创建集合 TreeSet<String> treeSet = new TreeSet<>()
添加元素 treeSet.add();
删除元素 treeSet.remove();
遍历 1. 增强for 2. 迭代器
判断 treeSet.contains();
**补充:**TreeSet集合的使用
Comparator 实现定制比较(比较器)
Comparable 可比较的
实例一:
package Demo25;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @author fanqie
* @date 2021/3/25 -15:43
* TreeSet集合的使用
* 存储结构:红黑树
*/
public class Tree_Set {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("qqq");
treeSet.add("www");
treeSet.add("eee");
treeSet.add("qas");
System.out.println("元素个数"+treeSet.size());
System.out.println(treeSet.toString());
treeSet.remove("qqq");
System.out.println("删除后的元素个数"+treeSet.size());
System.out.println(treeSet.toString());
System.out.println("使用增强for循环遍历");
for (String s : treeSet) {
System.out.println(s.toString());
}
System.out.println("使用迭代器遍历");
Iterator<String> iterator = treeSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(treeSet.contains("aaa"));
System.out.println(treeSet.isEmpty());
}
}
public class Student implements Comparable<Student>{
//先按姓名来比,然后再按年龄比
@Override
public int compareTo(Student o) {
int n1 = this.getName().compareTo(o.getName());
int n2 = this.age-o.getAge();
return n1==0?n2:n1;
}
}
package Demo25;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @author fanqie
* @date 2021/3/25 -15:43
* TreeSet集合的使用
* 要求:元素必须要实现Comparable接口,compareTo()方法返回值为0,认为是重复元素
* 存储结构:红黑树
*/
public class Tree_Set02 {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>();
Student student = new Student("aaa",17);
Student student1 = new Student("bbb",17);
Student student2 = new Student("ccc",17);
Student student3 = new Student("ddd",17);
treeSet.add(student);
treeSet.add(student1);
treeSet.add(student2);
treeSet.add(student3);
System.out.println("元素个数:"+treeSet.size());
System.out.println(treeSet.toString());
//treeSet.remove(student);
//treeSet.remove( new Student("aaa",17));
//System.out.println("删除后的元素个数:"+treeSet.size());
// System.out.println("删除后:"+treeSet.toString());
System.out.println("================");
for (Student student4 : treeSet) {
System.out.println(student4.toString());
}
System.out.println("===============");
Iterator<Student> iterator = treeSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(treeSet.contains(student));
System.out.println(treeSet.isEmpty());
}
}
实例二:
package Demo25;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @author fanqie
* @date 2021/3/25 -15:43
* TreeSet集合的使用
* Comparator :实现定制比较(比较器)
* Comparable 可比较的
* 存储结构:红黑树
*/
public class Tree_Set03 {
public static void main(String[] args) {
//创建集合,并指定比较规则
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int n1 = o1.getAge()-o2.getAge();
int n2 = o2.getName().compareTo(o2.getName());
return n1==0?n2:n1;
}
});
Student student = new Student("aaa",17);
Student student1 = new Student("bbb",18);
Student student2 = new Student("ccc",19);
Student student3 = new Student("ddd",20);
treeSet.add(student);
treeSet.add(student1);
treeSet.add(student2);
treeSet.add(student3);
System.out.println("元素个数:"+treeSet.size());
System.out.println(treeSet.toString());
//treeSet.remove(student);
//treeSet.remove( new Student("aaa",17));
//System.out.println("删除后的元素个数:"+treeSet.size());
// System.out.println("删除后:"+treeSet.toString());
System.out.println("================");
for (Student student4 : treeSet) {
System.out.println(student4.toString());
}
System.out.println("===============");
Iterator<Student> iterator = treeSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(treeSet.contains(student));
System.out.println(treeSet.isEmpty());
}
}
按照字符串长度进行排序 :从短到长
package Demo25;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* @author fanqie
* @date 2021/3/25 -15:43
* TreeSet集合的使用
* 要求:使用TreeSet集合实现按照字符串长度进行排序
*/
public class Tree_Set04 {
public static void main(String[] args) {
//创建集合,并指定比较规则
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int n1 = o1.length() - o2.length();
int n2 = o1.compareTo(o2);
return n1==0?n2:n1;
}
});
//添加数据
treeSet.add("helloworle");
treeSet.add("hellp");
treeSet.add("woaini");
treeSet.add("jiuxianglaochu");
treeSet.add("aidami");
treeSet.add("lubenwei");
System.out.println(treeSet.toString());
}
}
11.Map
Map接口的特点
-
用于存储任意键值对(key - value)
-
键:无序、无下标、不允许重复(唯一)
-
值:无序、无下标、允许重复
方法:
-
V put(K key, V value) 将对象存到集合中,关联键值
-
Object get(Object key) 根据键获得对应的值
-
Set 返回所有的Key
-
Collection values() 返回包含所有值的Collection集合
-
Set<Map.Entry<K, V>> 键值匹配的Set集合
Map接口的使用
package Demo25;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author fanqie
* @date 2021/3/25 -16:40
* Map接口的使用
* 特点:1.存储键值对 2.键不能重复,值可以重复 3.无序
*/
public class Map_01 {
public static void main(String[] args) {
//创建Map集合
Map<String,String> map = new HashMap<>();
//1.添加元素
//重复的值会替换相同重复值的第一个
map.put("番茄","帅气");
map.put("番茄1","帅气");
map.put("番茄2","帅气");
map.put("番茄3","帅气");
System.out.println("元素个数:"+map.size());
System.out.println(map.toString());
//2.删除
map.remove("番茄3");
System.out.println("删除之后:"+map.size());
System.out.println(map.toString());
//3.1.遍历
//3.1.使用KeySet()
System.out.println("==============使用KeySet()遍历================");
//Set<String> strings = map.keySet();
for (String key : map.keySet()) {
System.out.println(key+"---------"+map.get(key));
}
//3.2.使用entrySet()方法
System.out.println("==============使用entrySet()遍历================");
//Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+"--------------"+entry.getValue());
}
//4.判断
System.out.println(map.containsKey("番茄"));
System.out.println(map.containsValue("帅气"));
}
}
12.HashMap
存储结构:哈希表(数组+链表+红黑树)
使用key可使hashcode和equals作为重复
增、删、遍历、判断与上述一致
原码分析总结:
- HashMap刚创建时,table是null,节省空间,当添加第一个元素时,table容量调整为16
- 当元素个数大于阈值(16*0.75 = 12)时,会进行扩容,扩容后的大小为原来的两倍,目的是减少调整元素的个数
- jdk1.8 当每个链表长度 >8 ,并且数组元素个数 ≥64时,会调整成红黑树,目的是提高效率
- jdk1.8 当链表长度 <6 时 调整成链表
- jdk1.8 以前,链表时头插入,之后为尾插入
package Demo25;
import java.util.HashMap;
import java.util.Map;
/**
* @author fanqie
* @date 2021/3/25 -22:56
* HashMap集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
* 使用key可使hashcode和equals作为重复
*
*
*/
public class Hash_Map01 {
public static void main(String[] args) {
//创建集合
HashMap<Person, String> hashmap = new HashMap<Person, String>();
//1.添加元素
Person person = new Person("孙悟空",100);
Person person1 = new Person("猪八戒",101);
Person person2 = new Person("蔡徐坤",102);
hashmap.put(person,"广东");
hashmap.put(person1,"深圳");
hashmap.put(person2,"上海");
hashmap.put(new Person("孙悟空",100),"广东");
System.out.println("元素个数:"+hashmap.size());
System.out.println(hashmap.toString());
//2.删除
hashmap.remove(person);
System.out.println("删除之后的元素个数:"+hashmap.size());
System.out.println(hashmap.toString());
//3.遍历
//3.1.使用keySet()
System.out.println("========================使用keySet()===================");
for (Person person3 : hashmap.keySet()){
System.out.println(person3.toString()+"==========="+hashmap.get(person3));
}
//3.2.使用entrySet()
System.out.println("========================使用entrySet()===================");
for (Map.Entry<Person,String> entry : hashmap.entrySet()){
System.out.println(entry.getKey()+"============="+entry.getValue());
}
//4.判断
System.out.println(hashmap.containsKey(person2));
System.out.println(hashmap.containsValue("广西"));
}
}
13.HashTable
线程安全,运行效率慢;不允许null作为key或是value
14.Properties
hashtable的子类,要求key和value都是string,通常用于配置文件的读取
15.TreeMap
实现了SortedMap接口(是map的子接口),可以对key自动排序
16.Colletions工具类
**概念:**集合工具类,定义了除了存取以外的集合常用方法
直接二分查找int i = Collections.binarySearch(list, x);
成功返回索引
其他方法 : copy复制、reverse反转、shuffle打乱
package Demo25;
import java.util.*;
/**
* @author fanqie
* @date 2021/3/20 -15:45
* Colletions工具类
*/
public class collection3 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(200);
list.add(20);
list.add(40);
list.add(55);
list.add(6);
//sort排序
System.out.println("排序之前"+list.toString());
Collections.sort(list);
System.out.println("排序之后:"+list.toString());
//binarySearch二分查找 查找元素所在的位置
int i = Collections.binarySearch(list,6);
System.out.println(i);
//copy复制
List<Integer> objects = new ArrayList<>();
for (int j = 0; j <list.size() ; j++) {
objects.add(0);
}
Collections.copy(objects,list);
System.out.println(objects.toString());
//reverse反转
Collections.reverse(list);
System.out.println("反转之后:"+list.toString());
//shuffle打乱
Collections.shuffle(list);
System.out.println("打乱之后:"+list.toString());
//补充:list转成数组
System.out.println("=================list转成数组==================");
Integer[] iterators = list.toArray(new Integer[10]);
System.out.println(iterators.length);
System.out.println(Arrays.toString(iterators));
//数组转成集合
// 此时为受限集合,不能 添加和删除!
System.out.println("==================数组转成集合======================");
String[] names = {"张三","李四","王五"};
List<String> list2 = Arrays.asList(names);
System.out.println(list2);
// 把基本类型数组转为集合时,需要修改为包装类
Integer[] nums = {100, 200, 300, 400, 500};
List<Integer> list3 = Arrays.asList(nums);
System.out.println(list3);
}
}