概念
对象的容器,定义了对多个对象进行操作的常用方法,可实现数组的功能
和数组的区别
-
数组长度固定,集合长度不固定
-
数组可存储基本类型和引用类型,集合只能存储引用类型
collection父接口
特点:代表一组任意的对象,无序,无下标,不能重复
package com.collection.collection_1; public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object obj) { //1.判断是否为同一对象 if (this == obj) { return true; } //2.判断是否为空 if (obj == null) { return false; } //3.判断是否是Student类型 if (obj instanceof Student) { Student s = (Student) obj; //4.比较属性 if (this.name.equals(s.getName()) && this.age==s.getAge()) { return true; } } //5.不满足条件返回false return false; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
package com.collection.collection_1; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * Collection接口的使用 * (1)添加元素 * (2)删除元素 * (3)遍历元素 * (4)判断 * @author Pan */ public class Demo01 { public static void main(String[] args) { //创建集合 Collection collection = new ArrayList(); // (1)添加元素 collection.add("苹果"); collection.add("西瓜"); collection.add("榴莲"); //元素个数 System.out.println("元素个数:"+collection.size()); System.out.println(collection); // (2)删除元素 // collection.remove("榴莲"); // collection.clear();//删除所有 // System.out.println("删除之后:"+collection.size()); // (3)遍历元素【重点】 //3.1 增强for循环 System.out.println("===========使用增强for循环============"); for (Object o : collection) { System.out.println(o); } System.out.println("===========迭代器============"); //3.2 迭代器(专门用来遍历结合的一种方式) //hasNext();有没有下一个元素 //next();获取下一个元素 //remove();删除当前元素 Iterator it = collection.iterator(); while (it.hasNext()){ String s = (String)it.next(); System.out.println(s); // collection.remove(s);迭代过程中不能使用collection的删除方法 // it.remove();//正确使用迭代器的删除 } System.out.println(collection.size()); // (4)判断 System.out.println(collection.contains("西瓜"));//判断是否含有“西瓜” System.out.println(collection.isEmpty());//判断是否为空 } }
package com.collection.collection_1; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * Collection的使用:保存学生信息 * @author Pan */ public class Demo02 { public static void main(String[] args) { //新建collection对象 Collection collection = new ArrayList(); Student s1 = new Student("张三",20); Student s2 = new Student("张无忌",21); Student s3 = new Student("王二",22); //1.添加数据 collection.add(s1); collection.add(s2); collection.add(s3); // collection.add(s3);//可添加重复数据 System.out.println("元素个数:"+collection.size()); System.out.println(collection.toString()); //2.删除 collection.remove(s1); // collection.remove(new Student("王二",22));//使用错误 // collection.clear();//清除之后,对象还存在于堆里并没有被删除 System.out.println("删除之后:"+collection.size()); //3.遍历 //3.1 增强for System.out.println("==============增强for================"); for (Object o : collection) { Student s = (Student) o; System.out.println(s.toString()); } //3.2 迭代器 System.out.println("===============迭代器================"); Iterator it = collection.iterator(); while (it.hasNext()){ Student s = (Student) it.next(); System.out.println(s.toString()); } //4.判断 System.out.println(collection.contains(s2)); System.out.println(collection.isEmpty()); } }
List子接口
特点:有序,有下标,元素可以重复
package com.collection.collection_1; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * List接口的使用 * 特点:有序、有下标、元素可以重复 * @author Pan */ public class Demo03 { public static void main(String[] args) { //先创建集合对象 List list = new ArrayList<>(); //1.添加元素 list.add("苹果"); list.add("小米"); list.add(0,"华为"); System.out.println("元素个数:"+list.size()); System.out.println(list.toString()); //2.删除元素 // list.remove("苹果"); // list.remove(0); // list.clear(); // System.out.println("元素个数:"+list.size()); // System.out.println(list.toString()); //3.遍历 //3.1 使用for遍历 System.out.println("===============for=============="); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i));//get根据角标获取元素 } //3.1 使用增强for遍历 System.out.println("=============增强for=============="); for (Object o : list) { System.out.println(o); } //3.1 使用迭代器遍历 System.out.println("===============迭代器=============="); Iterator it = list.iterator(); while (it.hasNext()){ System.out.println(it.next()); } //3.1 使用列表迭代器遍历:和Iterator的区别,ListIterator可以向前或向后遍历,添加,删除,修改元素 System.out.println("=============列表迭代器=============="); ListIterator lit = list.listIterator(); System.out.println("====从前往后====="); while (lit.hasNext()){ System.out.println(lit.nextIndex()+":"+lit.next()); } System.out.println("====从后往前====="); while (lit.hasPrevious()){ System.out.println(lit.previousIndex()+":"+lit.previous()); } //4.判断 System.out.println(list.contains("苹果")); System.out.println(list.isEmpty()); //5.获取位置 System.out.println(list.indexOf("华为")); } }
package com.collection.collection_1; import java.util.ArrayList; import java.util.List; /** * List的使用 * @author Pan */ public class Demo04 { 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(20);//表示下标删除 // list.remove(new Integer(20)); list.remove(list.indexOf(20)); System.out.println("元素个数:"+list.size()); System.out.println(list.toString()); //补充方法subList:返回子集合,含左不含右 List subList = list.subList(1, 3); System.out.println(subList.toString()); } }
List实现类
-
ArrayList(重点)
-
数组结构实现,查询快,增删慢
-
jdk1.2版本,运行效率快,线程不安全
-
ArrayList源码分析
-
DeFAULT-CAPACITY = 10;默认容量为10
-
如没有向集合中添加元素时用量为0,添加一个后10;每次扩容大小是原来的1.5倍
-
elementData:存放元素的数组
-
size():实际元素个数
-
add():添加元素
-
-
package com.collection.collection_1; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; /** * ArrayList的使用 * 存储结构:数组,查找遍历速度快,增删慢 * @author Pan */ public class Demo05 { public static void main(String[] args) { //创建集合 ArrayList arrayList = new ArrayList<>(); //1.添加元素 Student s1 = new Student("aaa", 12); Student s2 = new Student("bbb", 13); Student s3 = new Student("ccc", 14); Student s4 = new Student("ddd", 15); Student s5 = new Student("eee", 16); Student s6 = new Student("fff", 17); arrayList.add(s1); arrayList.add(s2); arrayList.add(s3); arrayList.add(s4); arrayList.add(s5); arrayList.add(s6); System.out.println("元素个数:"+arrayList.size()); System.out.println(arrayList.toString()); //2.删除元素 // arrayList.remove(s1); arrayList.remove(new Student("aaa", 12));//重写了equals方法后,可实现删除 System.out.println("元素个数:"+arrayList.size()); System.out.println(arrayList.toString()); // arrayList.clear(); // System.out.println("元素个数:"+arrayList.size()); // System.out.println(arrayList.toString()); //3.遍历元素【重点】 System.out.println("===============for============="); for (int i = 0; i < arrayList.size(); i++) { System.out.println(arrayList.get(i)); } System.out.println("=============增强for============="); for (Object o : arrayList) { System.out.println(o); } System.out.println("=============迭代器============="); Iterator iterator = arrayList.iterator(); while (iterator.hasNext()){ Student s = (Student) iterator.next(); System.out.println(s.toString()); } System.out.println("=============列表迭代器============="); ListIterator listIterator = arrayList.listIterator(); System.out.println("====从前往后===="); while (listIterator.hasNext()){ Student s = (Student) listIterator.next(); System.out.println(s.toString()); } System.out.println("====从后往前===="); while (listIterator.hasPrevious()){ System.out.println(listIterator.previousIndex()+":"+listIterator.previous()); } //4.判断 System.out.println(arrayList.contains(s1)); System.out.println(arrayList.contains(new Student("ccc", 14))); System.out.println(arrayList.isEmpty()); //5.查找 System.out.println(arrayList.indexOf(new Student("ccc", 14))); } }
package com.collection.collection_2; import com.collection.collection_1.Student; import java.util.ArrayList; import java.util.Iterator; public class Demo03 { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("xxx"); arrayList.add("yyy"); // arrayList.add(10); // arrayList.add(20); for (String s : arrayList) { System.out.println(s); } ArrayList<Student> arrayList1 = new ArrayList<Student>(); Student s1 = new Student("刘德华", 12); Student s2 = new Student("郭富城", 13); Student s3 = new Student("梁朝伟", 14); arrayList1.add(s1); arrayList1.add(s2); arrayList1.add(s3); Iterator<Student> it = arrayList1.iterator(); while (it.hasNext()){ Student s = it.next(); System.out.println(s.toString()); } } }
-
vector
-
数组结构实现,查询快,增删慢
-
jdk1.0版本,运行效率慢,线程安全
-
package com.collection.collection_2; import java.util.Enumeration; import java.util.Iterator; import java.util.ListIterator; import java.util.Vector; /** * 演示Vector集合的使用 * 存储结构:数组 * @author Pan */ public class Demo01 { public static void main(String[] args) { //创建集合 Vector vector = new Vector<>(); //1.添加元素 vector.add("草莓"); vector.add("芒果"); vector.add("西瓜"); System.out.println("元素个数:"+vector.size()); //2.删除 // vector.remove(0); // vector.remove("西瓜"); // vector.clear(); // System.out.println("元素个数:"+vector.size()); //3.遍历 System.out.println("=====================遍历----for======================"); for (int i = 0; i < vector.size(); i++) { System.out.println(vector.get(i)); } System.out.println("=====================遍历----增强for======================"); for (Object o : vector) { System.out.println(o); } System.out.println("=====================遍历----迭代器======================"); Iterator it = vector.iterator(); while (it.hasNext()){ System.out.println(it.next().toString()); } System.out.println("=====================遍历----列表迭代器======================"); ListIterator lit = vector.listIterator(); System.out.println("============================================================"); while (lit.hasNext()){ System.out.println(lit.next().toString()); } System.out.println("============================================================"); while (lit.hasPrevious()){ System.out.println(lit.previousIndex()+":"+lit.previous()); } System.out.println("=====================遍历----枚举器======================"); Enumeration en = vector.elements(); while (en.hasMoreElements()){ String o = (String) en.nextElement(); System.out.println(o); } //4.判断 System.out.println("=====================判断======================"); System.out.println(vector.contains("西瓜")); System.out.println(vector.isEmpty()); //5.vector其他方法 System.out.println(vector.firstElement());//获取第一个元素 System.out.println(vector.lastElement());//获取最后一个元素 System.out.println(vector.elementAt(1));//获取指定下标元素 System.out.println(vector.get(2));//获取指定下标元素 } }
-
LinkedList
-
链表结构实现,增删快,查询慢
package com.collection.collection_2; import com.collection.collection_1.Student; import javax.lang.model.element.Element; import javax.xml.stream.events.EndElement; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; /** * LinKedList的使用 * 存储结构:双向链表 * @author Pan */ public class Demo02 { public static void main(String[] args) { //创建集合 LinkedList linkedList = new LinkedList<>(); //1.添加元素 Student s1 = new Student("aaa", 12); Student s2 = new Student("bbb", 13); Student s3 = new Student("ccc", 14); Student s4 = new Student("ddd", 15); Student s5 = new Student("eee", 16); Student s6 = new Student("fff", 17); linkedList.add(s1); linkedList.add(s2); linkedList.add(s3); linkedList.add(s4); linkedList.add(s5); linkedList.add(s6); System.out.println("元素个数:"+linkedList.size()); System.out.println(linkedList.toString()); //2.删除 // linkedList.remove(s1); // System.out.println("删除后元素个数:"+linkedList.size()); // linkedList.clear(); //3.遍历 System.out.println("==================for================"); for (int i = 0; i < linkedList.size(); i++) { System.out.println(linkedList.get(i)); } System.out.println("==================增强for循环================"); for (Object o : linkedList) { System.out.println(o); } System.out.println("==================迭代器==============="); Iterator it = linkedList.iterator(); while (it.hasNext()){ Student s = (Student) it.next(); System.out.println(s); } System.out.println("==================列表迭代器==============="); ListIterator lit = linkedList.listIterator(); System.out.println("=========从前往后=========="); while (lit.hasNext()){ Student s = (Student) lit.next(); System.out.println(s); } System.out.println("=========从前往后=========="); while (lit.hasPrevious()){ System.out.println(lit.previousIndex()+":"+ lit.previous()); } //4.判断 System.out.println("==================判断==============="); System.out.println(linkedList.contains(s2)); System.out.println(linkedList.isEmpty()); //5.获取 System.out.println(linkedList.indexOf(s3)); } }
-
-
ArrayList和LinkedList区别
-
ArrayList:数组 必须开辟连续空间
-
LinkedList:链表 无序开辟连续空间
-
泛型
-
本质是参数化类型,把类型作为参数传递
-
常见形式:泛型类、泛型接口、泛型方法
-
好处:
-
提高代码的重用性
-
防止类型转换异常,提高代码安全性
-
package com.collection.collection_2; /** * 泛型类 * 语法,类名<T> * T是类型占位符,表示一种引用类型,如果编写多个使用逗号隔开 * @author Pan */ 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 com.collection.collection_2; /** * 泛型方法 * 语法:<T> 返回值类型 * @author Pan */ public class MyGenericMethod { //泛型方法 public <T> T show(T t){ System.out.println("泛型方法:"+t); return t; } }
package com.collection.collection_2; /** * 泛型接口 * 语法,接口名<T> * 注意:不能创建泛型静态常量 * @author Pan */ public interface MyInterface<T> { String name = "张三"; T server(T t); }
package com.collection.collection_2; public class MyInterfaceImpl implements MyInterface<String>{ @Override public String server(String t) { System.out.println(t); return t; } }
package com.collection.collection_2; public class MyInterfaceImpl2<T> implements MyInterface<T>{ @Override public T server(T t) { System.out.println(t); return t; } }
package com.collection.collection_2; public class TestGeneric { public static void main(String[] args) { //使用泛型类创建对象 /* 注意: 1.泛型只能使用引用类型 2.不同泛型不能相互赋值 */ MyGeneric<String> myGeneric = new MyGeneric<String>(); myGeneric.t = "Hello"; myGeneric.show("大家好,加油"); String string = myGeneric.getT(); MyGeneric<Integer> myGeneric2 = new MyGeneric<>(); myGeneric2.t = 100; myGeneric2.show(200); Integer integer = myGeneric2.getT(); //泛型接口的泛型 MyInterfaceImpl impl = new MyInterfaceImpl(); impl.server("XXXXXXXX"); MyInterfaceImpl2<Integer> impl2 = new MyInterfaceImpl2<>(); impl2.server(1000); //泛型方法 MyGenericMethod myGenericMethod = new MyGenericMethod(); myGenericMethod.show("李四"); myGenericMethod.show(200); myGenericMethod.show(3.14); } }
泛型集合
-
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致
-
特点:
-
编译时即可检查,而非运行时抛出异常
-
访问时,不必类型转换(拆箱)
-
不同泛型之间引用不能相互赋值,泛型不存在多态
-
set子接口
-
特点:无序、无下标、元素不可重复
-
方法:全部继承自Collection中的方法
package com.collection.collection_3; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * 测试Set接口的使用 * 特点: * 1.无序、无下标 * 2.不能重复 * @author Pan */ public class Demo01 { public static void main(String[] args) { //创建集合 Set<String> set = new HashSet<>(); //1.添加数据 set.add("小米"); set.add("苹果"); set.add("华为"); System.out.println("数据个数:"+set.size()); System.out.println(set.toString()); //2.删除 // set.remove("小米"); //3.遍历 System.out.println("=========增强for========="); for (String s : set) { System.out.println(s); } System.out.println("=========迭代器========="); Iterator<String> it = set.iterator(); while (it.hasNext()){ System.out.println(it.next()); } //4.判断 System.out.println(set.contains("小米")); System.out.println(set.isEmpty()); } }
set实现类
-
HashSet
-
基于HashCode计算元素存放的位置
-
当存入元素的哈希码相同时,会调用equals确认,如结果为true,则拒绝后者存入
package com.collection.collection_3; import java.util.HashSet; import java.util.Iterator; /** * HashSet集合的使用 * 存储结构:哈希表(数组+链表+红黑树) * * @author Pan */ public class Demo02 { public static void main(String[] args) { //新建集合 HashSet<String> hashSet = new HashSet<>(); //1.添加元素 hashSet.add("刘德华"); hashSet.add("梁朝伟"); hashSet.add("郭富城"); hashSet.add("黎明"); System.out.println("元素个数:"+hashSet.size()); System.out.println(hashSet.toString()); //2.删除 // hashSet.remove("刘德华"); // System.out.println("删除之后元素个数:"+hashSet.size()); //3.增强for System.out.println("=========增强for========="); for (String s : hashSet) { System.out.println(s); } System.out.println("=========迭代器========="); Iterator<String> it = hashSet.iterator(); while (it.hasNext()){ System.out.println(it.next()); } //4.判断 System.out.println(hashSet.contains("刘德华")); System.out.println(hashSet.isEmpty()); } }
-
package com.collection.collection_3; import java.util.HashSet; import java.util.Iterator; /** * HashSet集合的使用 * 存储结构:哈希表(数组+链表+红黑树) * 存储过程: * (1)根据hashcode计算保存的位置,如果此位置为空,则直接保存,如果不为空执行第二部 * (2)在执行equals方法,如果equals方法为true,则认为是重复,否则,形成链表 * @author Pan */ public class Demo03 { public static void main(String[] args) { //创建集合 HashSet<Person> persons = new HashSet<>(); //1.添加数据 Person p1 = new Person("刘德华", 20); Person p2 = new Person("郭富城", 20); Person p3 = new Person("梁朝伟", 20); Person p4 = new Person("黎明", 20); persons.add(p1); persons.add(p2); persons.add(p3); persons.add(p4); persons.add(new Person("刘德华",20)); System.out.println("元素个数:"+persons.size()); System.out.println(persons.toString()); //2.删除 // persons.remove(p1); // persons.clear(); // System.out.println("删除之后元素个数:"+persons.size()); // System.out.println(persons.toString()); //3.遍历 System.out.println("===========增强for==========="); for (Person person : persons) { System.out.println(person.toString()); } System.out.println("===========迭代器==========="); Iterator<Person> it = persons.iterator(); while (it.hasNext()){ System.out.println(it.next()); } //4.判断 System.out.println(persons.contains(p2)); System.out.println(persons.isEmpty()); } }
-
TreeSet
-
基于排列顺序实现元素不重复
-
实现了SortedSet接口,对集合元素自动排序
-
元素对象的类型必须实现comparable接口,指定排序规则
-
通过CompareTo方法确定是否为元素重复
package com.collection.collection_3; import java.util.Iterator; import java.util.TreeSet; /** * TreeSet的使用 * 存储结构:红黑树 * @author Pan */ public class Demo04 { public static void main(String[] args) { //创建集合 TreeSet<String> treeSet = new TreeSet<>(); //1.添加元素 treeSet.add("xyz"); treeSet.add("abc"); treeSet.add("hello"); // treeSet.add("xyz"); System.out.println("元素个数:"+treeSet.size()); System.out.println(treeSet.toString()); //2.删除 treeSet.remove("xyz"); System.out.println("删除之后元素个数:"+treeSet.size()); //3.遍历 System.out.println("===========增强for==========="); for (String s : treeSet) { System.out.println(s.toString()); } System.out.println("===========迭代器==========="); Iterator<String> it = treeSet.iterator(); while (it.hasNext()){ System.out.println(it.next()); } //4.判断 System.out.println(treeSet.contains("abc")); System.out.println(treeSet.isEmpty()); } }
-
package com.collection.collection_3; import java.util.Objects; /** * 人类 * @author Pan */ public class Person implements Comparable<Person>{ private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { //源码中31为质数,可以减少散列冲突 //可以提高执行效率----31*i=(i<<5)-i return Objects.hash(name, age); } // @Override // public int hashCode() { // int n1 = this.name.hashCode(); // int n2 = this.age; // return n1+n2; // } // // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Person person = (Person) o; // return age == person.age && name.equals(person.name); // } @Override public String toString() { return "Person{" + "name=" + name + ", age=" + age + '}'; } //先比较姓名,再比较年龄 @Override public int compareTo(Person o) { int n1 = this.getName().compareTo(o.getName()); int n2 = this.age - o.getAge(); return n1==0?n2:n1; } }
package com.collection.collection_3; import java.util.Iterator; import java.util.TreeSet; /** * 使用TreeSet保存数据 * 存储结构:红黑树 * 要求:元素必须实现Comparable接口,CompareTo()方法返回值为0,认为是重复元素 * @author Pan */ public class Demo05 { public static void main(String[] args) { //创建集合 TreeSet<Person> persons = new TreeSet<>(); Person p1 = new Person("刘德华", 20); Person p2 = new Person("郭富城", 20); Person p3 = new Person("梁朝伟", 20); Person p4 = new Person("黎明", 20); persons.add(p1); persons.add(p2); persons.add(p3); persons.add(p4); System.out.println("元素个数:"+persons.size()); System.out.println(persons.toString()); //2.删除 // persons.remove(p1); // persons.clear(); // System.out.println("删除之后元素个数:"+persons.size()); // System.out.println(persons.toString()); //3.遍历 System.out.println("===========增强for==========="); for (Person person : persons) { System.out.println(person.toString()); } System.out.println("===========迭代器==========="); Iterator<Person> it = persons.iterator(); while (it.hasNext()){ System.out.println(it.next()); } //4.判断 System.out.println(persons.contains(p2)); System.out.println(persons.isEmpty()); } }
package com.collection.collection_3; import java.util.Comparator; import java.util.TreeSet; /** * TreeSet集合的使用 * Comparator:实现定制比较(比较器) * Comparable:可比较的 * @author Pan */ public class Demo06 { public static void main(String[] args) { //创建集合并指定比较规则(通过指定后可以不用实现接口) TreeSet<Person> persons = new TreeSet<>(new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { int n1 = o1.getAge() - o2.getAge(); int n2 = o1.getName().compareTo(o2.getName()); return n1==0?n2:n1; } }); Person p1 = new Person("刘德华", 20); Person p2 = new Person("郭富城", 21); Person p3 = new Person("梁朝伟", 25); Person p4 = new Person("黎明", 23); persons.add(p1); persons.add(p2); persons.add(p3); persons.add(p4); System.out.println("元素个数:"+persons.size()); System.out.println(persons.toString()); } }
package com.collection.collection_3; import java.util.Comparator; import java.util.TreeSet; /** * 要求:使用TreeSet集合实现字符串按照长度进行排序 * Comparator实现定制比较 * @author Pan */ public class Demo07 { public static void main(String[] args) { TreeSet<String> strings = 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; } }); strings.add("helloworld"); strings.add("zhang"); strings.add("lisi"); strings.add("wangwu"); strings.add("beijing"); strings.add("xian"); strings.add("nanjing"); System.out.println(strings.toString()); } }
Map父接口
特点:存储一对数据、无序、无下标,键不可重复,值可重复
package com.collection.collection_4; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Map接口的使用 * 特点: * (1)存储键值对 * (2)键不能重复,值可以重复 * (3)无序 * @author Pan */ public class Demo01 { public static void main(String[] args) { //创建Map集合 Map<String,String> map = new HashMap<>(); //1.添加元素 map.put("cn","中国"); map.put("uk","英国"); map.put("usa","美国"); map.put("cn","zhongguo"); System.out.println("元素个数:"+map.size()); System.out.println(map.toString()); //2.删除 // map.remove("usa"); // System.out.println("删除之后元素个数:"+map.size()); //3.遍历 System.out.println("================使用keySet()=============="); Set<String> keySet = map.keySet(); for (String key : map.keySet()) { System.out.println(key+"--------"+map.get(key)); } System.out.println("==========迭代器(补充)==========="); Iterator<String> it = keySet.iterator(); while (it.hasNext()){ String s = it.next(); System.out.println(s+"---------"+map.get(s));//一次循环不能使用两次next() } 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("cn")); System.out.println(map.containsValue("泰国")); } }
Map集合的实现类
-
HashMap
线程不安全,运行效率快;允许null,作为key或者value
package com.collection.collection_4; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * HashMap集合的使用 * 存储结构:哈希表(数组+链表+红黑树) * 使用key的hashcode和equals判断重复 * * HashMap源码总结: * (1)HashMap刚创建时,table是null,为了节省空间,table容量调整为16 * (2)当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容之后大小为原来的两倍。目的是减少调整元素的个数 * (3)jdk1.8当每个链表长度大于8,并且元素个数大于等于64时,会调整为红黑树,目的时提高执行效率 * (4)jdk1.8当链表长度小于6时,调整成链表 * (5)jdk1.8以前,链表是头插入,jdk1.8以后,链表是尾插入 * * @author Pan */ public class Demo02 { public static void main(String[] args) { //创建集合 HashMap<Student, String> students = new HashMap<>(); //1.添加元素 Student s1 = new Student("刘德华", 20); Student s2 = new Student("郭富城", 21); Student s3 = new Student("梁朝伟", 22); Student s4 = new Student("黎明", 23); students.put(s1,"北京"); students.put(s2,"四川"); students.put(s3,"上海"); students.put(s4,"杭州"); // students.put(new Student("黎明", 23),"杭州");//重写hashcode和equals方法后添加失败 System.out.println("元素个数:"+students.size()); System.out.println(students.toString()); //2.删除 students.remove(s1); System.out.println("删除之后元素个数:"+students.size()); //3.遍历 System.out.println("====================使用keySet()==================="); for (Student s : students.keySet()) { System.out.println(s+"------"+students.get(s)); } System.out.println("============使用keySet()迭代器================"); Set<Student> set = students.keySet(); Iterator<Student> it = set.iterator(); while (it.hasNext()){ Student s = it.next(); System.out.println(s+"------"+students.get(s)); } System.out.println("====================使用entrySet()==================="); for (Map.Entry<Student, String> entry : students.entrySet()) { System.out.println(entry.getKey()+"------"+entry.getValue()); } System.out.println("============使用entrySet()迭代器================"); Set<Map.Entry<Student, String>> entries = students.entrySet(); Iterator<Map.Entry<Student, String>> iterator = entries.iterator(); while (iterator.hasNext()){ Map.Entry<Student, String> entry = iterator.next(); System.out.println(entry.getKey()+"------"+entry.getValue()); } //4.判断 System.out.println(students.containsKey(s1)); System.out.println(students.containsValue("杭州")); } }
-
Hashtable-----使用少
线程安全,运行效率慢;不允许null,作为key或者value
-
Properties:
Hashtable的子类,要求key和value都是String,通常用于配置文件的读取
-
TreeMap
package com.collection.collection_4; import java.util.*; /** * TreeMap的使用 * 存储结构:红黑树 * @author Pan */ public class Demo03 { public static void main(String[] args) { //新建集合 TreeMap<Student, String> treeMap = new TreeMap<>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int n1= o1.getStuNo() - o2.getStuNo(); return n1; } }); //添加元素 Student s1 = new Student("刘德华", 20); Student s2 = new Student("郭富城", 21); Student s3 = new Student("梁朝伟", 22); Student s4 = new Student("黎明", 23); treeMap.put(s1,"北京"); treeMap.put(s2,"浙江"); treeMap.put(s3,"成都"); treeMap.put(s4,"上海"); System.out.println("元素个数:"+treeMap.size()); System.out.println(treeMap.toString()); //2.删除 // treeMap.remove(s3); // System.out.println("删除之后元素个数:"+treeMap.size()); //3.遍历 System.out.println("====================使用keySet()==================="); for (Student s : treeMap.keySet()) { System.out.println(s+"------"+treeMap.get(s)); } System.out.println("============使用keySet()迭代器================"); Set<Student> set = treeMap.keySet(); Iterator<Student> it = set.iterator(); while (it.hasNext()) { Student s = it.next(); System.out.println(s+"------"+treeMap.get(s)); } System.out.println("====================使用entrySet()==================="); for (Map.Entry<Student, String> entry : treeMap.entrySet()) { System.out.println(entry.getKey()+"------"+entry.getValue()); } System.out.println("============使用entrySet()迭代器================"); Set<Map.Entry<Student, String>> entries = treeMap.entrySet(); Iterator<Map.Entry<Student, String>> entryIterator = entries.iterator(); while (entryIterator.hasNext()){ Map.Entry<Student, String> entry = entryIterator.next(); System.out.println(entry.getKey()+"------"+entry.getValue()); } //4.判断 System.out.println(treeMap.containsKey(s1)); System.out.println(treeMap.containsValue("杭州")); } }
Collections
集合工具类,定义了除了存取以外的集合的常用方法
package com.collection.collection_4; import java.util.Objects; public class Student { private String name; private int stuNo; public Student() { } public Student(String name, int stuNo) { this.name = name; this.stuNo = stuNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStuNo() { return stuNo; } public void setStuNo(int stuNo) { this.stuNo = stuNo; } @Override public String toString() { return "Student{" + "name=" + name + ", stuNo=" + stuNo + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return stuNo == student.stuNo && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, stuNo); } // @Override // public int compareTo(Student o) { // int n1= this.stuNo - o.getStuNo(); // return n1; // } }
package com.collection.collection_4; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * 演示Collections工具类的使用 * @author Pan */ public class Demo04 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(20); list.add(5); list.add(12); list.add(30); list.add(6); //sort排序 System.out.println("排序之前:"+list.toString()); Collections.sort(list); System.out.println("排序之后:"+list.toString()); //binarySearch:二分查找 int i = Collections.binarySearch(list, 12); System.out.println(i); //copy复制 ArrayList<Integer> dest = new ArrayList<>(); for (int j = 0; j < list.size(); j++) { dest.add(0); } Collections.copy(dest,list);//复制时必须保证两个集合长度一致 System.out.println("dest复制后:"+dest.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[] arr = list.toArray(new Integer[0]); System.out.println(arr.length); System.out.println(Arrays.toString(arr)); //数组转成集合 System.out.println("=========数组转成集合==========="); String[] names = {"张三","李四","王五"}; //集合为受限集合,不能添加和删除 List<String> list1 = Arrays.asList(names); System.out.println(list1); //把基本数据类型转成集合时,需要修改为包装类型 Integer[] nums = {100,200,300,400,500}; List<Integer> list2 = Arrays.asList(nums); System.out.println(list2); } }