- 集合框架Collection
- 什么是集合
- collection的使用(1)ArrayList
- Collection的使用2ArrayList
- List的使用(ArrsyList)
- List实现类
- ArrarList内部是数组实现
- ArrayList源码分析
- Vector
- linkedList:链表
- linkedList源码分析
- 泛型
- 泛型类
- 泛型接口
- 泛型方法
- 泛型集合
- set接口使用
- HashSet
- 重写hashCode与equals&&存储过程
- TreeSet
- TreeSet第一种实现方法,利用元素实现Comparable
- TreeSet第二种实现方法,利用含参构造Comparator
- 案例
- Map
- Map接口的使用
- HashMap
- Hashtable
- TreeMap
- Collections工具类
- Collection总结
集合不能存储基本类型(自动装箱)
- 对象的容器,实现了对对象的常用操作,类似数组功能。
- 集合与数组的区别
数组长度固定,集合长度不固定
数组可以存储基本类型与引用类型,集合只能存放引用类型
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yVGHdufT-1635068326792)(D:学习截图2191.PNG)]
collection的使用(1)ArrayListpackage com.jiateng.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
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());//size 返回元素个数
System.out.println(collection.toString());
// * 2.删除元素
// collection.remove("苹果");
// System.out.println(collection);
// collection.clear();
// System.out.println(collection.size());
// * 3.遍历元素 重点
//1.使用增强for循环
for (Object o : collection) {
System.out.println(o);
}
System.out.println("___________分割线__________");
//2.使用Iterator迭代器(一种遍历集合的方式)(调用iterator方法,返回Iterator类型)
// Iterator由三个方法组成
// 1.hasNext()有没有下一个元素
// 2.next()获取下一个元素,指针后移
// 3.remove()删除当前元素
Iterator iterator = collection.iterator();
while (iterator.hasNext()){//在迭代器运行过程中不允许,使用Collection的方法。
// 异常 ConcurrentModificationException 并发修改异常
String next = (String)iterator.next();//如果知道元素的类型,在这里可以强制转换(此处可以转String)
System.out.println(next);
// iterator.remove();
//在迭代器运行过程中,可以使用Iterator的方法。
}
// * 4.判断
System.out.println(collection.contains("香蕉"));//判断是否存在
System.out.println(collection.isEmpty());//判断是否为空
}
}
Collection的使用2ArrayList
package com.jiateng.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo02 {
public static void main(String[] args) {
Collection collection =new ArrayList();
Studente s1 = new Studente("张三", 20);//创建对象
Studente s2 = new Studente("李四", 22);
Studente s3 = new Studente("王五", 26);
//添加元素
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println("元素个数为:"+collection.size());
System.out.println(collection.toString());//在studente类中重写了toString方法
//删除
// collection.remove(new Studente("张三",20));
// System.out.println(collection);
// collection.clear();
// System.out.println(collection.size());
// System.out.println(collection);
//遍历
//(1)增强for循环遍历
for (Object o : collection) {
System.out.println(o);
}
System.out.println("=+++++++===迭代器=============");
//(2)使用迭代器遍历 Iterator的三个方法 hasNext next remove
Iterator iterator=collection.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//判断
System.out.println(collection.contains(s1));
System.out.println(collection.isEmpty());
}
}
class Studente{
private String name;
private int age;
//构造器
public Studente(String name,int age) {
this.name = name;
this.age = age;
}
//get set 方法
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;
}
//重写toString 方法
@Override
public String toString() {
return "Studente{" + "name='" + name + ''' + ", age=" + age + '}';
}
}
List的使用(ArrsyList)
package com.jiateng.collection.List;
import java.util.*;
public class Demo01 {
public static void main(String[] args) {
List list = new ArrayList();
//1.添加元素
list.add("小米");
list.add("苹果");
list.add(2,"华为");//前面的下标,不能大于所在位置的下标
System.out.println(list);
// //2.删除
// list.remove(0);//可以直接删脚标
// System.out.println(list);
//3.遍历 *****8
System.out.println("_________3.1 for循环遍历______");
for (int i=0;i
List实现类
ArrarList内部是数组实现
package com.jiateng.collection.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ListIterator;
public class Demo03 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
//添加元素
Studente s1=new Studente("刘德华",20);
Studente s2=new Studente("郭富城",24);
Studente s3=new Studente("成龙",22);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println(arrayList);
System.out.println("元素个数为:"+arrayList.size());
//删除元素
arrayList.remove(new Studente("刘德华",20));
System.out.println("-------------------------");
System.out.println(arrayList);
//遍历元素
System.out.println("使用迭代器");
ListIterator list = arrayList.listIterator();
while(list.hasNext()){
System.out.println(list.next());
}
System.out.println("------------使用列表迭代器-----------");
while(list.hasPrevious()){
System.out.println(list.previous().toString());
}
}
}
class Studente{
private String name;
private int age;
//构造器
public Studente(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;
}
//重写toString方法
@Override
public String toString() {
return "名字为:"+name+"、年龄为:"+age;
}
//重写equals方法
@Override
public boolean equals(Object obj) {
if(this==obj)return true;
if(obj==null)return false;
if(obj instanceof Studente ){
Studente s1=(Studente)obj;
if(this.age==s1.age&& this.name==s1.name) return true;
}
return false;
}
}
ArrayList源码分析
注意:如果没有向集合中添加任何元素容量为零;添加任何一个元素之后为10;扩容1.5倍
elementData存放元素的数组
size实际元素个数
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData; //存放元素的数组(下称数组)
// non-private to simplify nested class access
private int size //实际大小
//无参构造器
public ArrayList() { //实例化时调用无参构造
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
=================================================================================
public boolean add(E e) { //如何实现添加元素,数组长度如何变化,看此方法!
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
==============================================================================
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
==============================================================================
//此方法作用:如果数组未存放元素(当前数组长度小于10也可以),那么将会返回一个参数10,
private static int calculateCapacity(Object[] elementData, {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
===============================================================================
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
==============================================================================
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length; //当前数组的长度
int newCapacity = oldCapacity + (oldCapacity >> 1);//>>转换成2进制后所有位数都移动
if (newCapacity - minCapacity < 0)//数组添加一个元素之后,数组长度变为10,自此开始再添加
//素,数组都会1.5倍增长(相当于x=x+x>>1),但是如果当前数组的1.5倍小于10,数组的长度还是为10;
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//newCapacity=10
}
Vector
package com.jiateng.collection.List;
import java.util.Enumeration;
import java.util.Vector;
public class Demo04 {
public static void main(String[] args) {
Vector vector = new Vector();
//添加
vector.add("苹果");
vector.add("香蕉");
vector.add("樱桃");
vector.add("西瓜");
System.out.println(vector);
//删除
// vector.remove(1);
// vector.remove("苹果");
// System.out.println(vector.size());
System.out.println("--------------使用枚举器遍历-----------------");
//遍历 使用枚举器遍历 (jdk1.2之前)
Enumeration elements = vector.elements(); //类似于迭代器
while(elements.hasMoreElements()){
System.out.println(elements.nextElement());
}
}
}
linkedList:链表
package com.jiateng.collection.List;
import java.util.Iterator;
import java.util.linkedList;
import java.util.ListIterator;
public class Demo05 {
public static void main(String[] args) {
linkedList linkedList = new linkedList();
Studente s1=new Studente("刘德华",20);
Studente s2=new Studente("郭富城",24);
Studente s3=new Studente("成龙",22);
//添加元素
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
System.out.println("元素个数为:"+linkedList.size());
System.out.println(linkedList.toString());
//删除元素
// linkedList.remove(new Studente("刘德华",20));
// System.out.println(linkedList.size());
//遍历
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()){
System.out.println(it.next());
}
System.out.println("---------列表迭代器遍历------------");
System.out.println("向后遍历");
ListIterator lis = linkedList.listIterator();
while(lis.hasNext()){
System.out.println(lis.next());
}
System.out.println("向前遍历");
while(lis.hasPrevious()){
System.out.println(lis.previous());
}
//判断
System.out.println(linkedList.contains(s2));
System.out.println(linkedList.isEmpty());//判空
//获取
System.out.println("获取");
System.out.println(linkedList.indexOf(s2));
}
}
linkedList源码分析
transient int size = 0;
transient Node first; //头指针
transient Node last; //尾指针
public linkedList() { //无参构造
}
=================================================================================
public boolean add(E e) {
linkLast(e);
return true;
}
=================================================================================
void linkLast(E e) {
final Node l = last;
final Node newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
=================================================================================
private static class Node {
E item; //item存放数据
Node next; //类似于指针域
Node prev;
Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
Node类结点 item存放元素
泛型
泛型:java泛型是jdk1.5中引入的一个新特性,其本质是参数化类型,吧类型作为参数传递。
常见形式有泛型类、泛型接口、泛型方法。
语法T称位类型占位符,表示一种引用类型。
E - Element (在集合中使用,因为集合中存放的是元素)
T - Type(Java 类)
K - Key(键)
V - Value(值)
N - Number(数值类型)
? - 表示不确定的java类型
好处:
- 提高代码的重用性
- 防止类型转化异常,提高代码的安全性
泛型类
package com.jiateng.collection.List;public class Demo06 { //注意:泛型可以创建变量,但是不可以实例化。 //原因:泛型传递的类型中构造方法的私有性不确定。 //1.使用泛型创建变量 public T t; //2.泛型作为方法的参数 public void say(T t){ System.out.println(t); } //3.泛型作为方法的返回值 public T getT(){ return t; }}
package com.jiateng.collection.List;public class Demo07 { public static void main(String[] args) { //1.只能是引用类型 2.不同泛型类型对象之间不能赋值 Demo06 s = new Demo06(); s.t="Holle"; s.say("你好加油!"); Demo06 in= new Demo06<>(); in.t=1000; in.say(800); Integer t = in.getT(); System.out.println(t); }}
泛型接口
package com.jiateng.collection.List;public interface Demo08 {String name="ji";T say(T t);}
package com.jiateng.collection.List;public class MyInterfacempl implements Demo08{//1.此处的占位符必须是类型 public MyInterfacempl(){ } @Override public String say(String t) { System.out.println(t); return t; }}
package com.jiateng.collection.List;public class MyIntegerfacempl implements Demo08{//2.当实现类也无法确定类型时,可以把实现类转成泛型类 @Override public T say(T t) { System.out.println(t); return null; }}
package com.jiateng.collection.List;public class Demo07 { public static void main(String[] args) { //1.只能是引用类型 2.不同泛型类型对象之间不能赋值 System.out.println("==================================="); MyIntegerfacempl inte = new MyIntegerfacempl<>(); inte.say(9882); }}
泛型方法
package com.jiateng.collection.List;public class Demo09 { int a; //泛型方法 public void show(T t){ System.out.println(t); }}class text01{ public static void main(String[] args) { Demo09 demo09 = new Demo09(); demo09.show("java");//此时我传什么类型泛型就是什么类型 demo09.show(100000); }}//提高复用性
泛型集合
概念:参数化类型、类型安全的集合强制集合的类型必须一致
package com.jiateng.collection.List;import java.util.linkedList;public class Demo10 { public static void main(String[] args) { linkedList obj = new linkedList(); obj.add("jiji"); // obj.add(1000)使用泛型数组只能存放一种数据类型 }}
set接口使用
特点:无序、无下标、元素不可重复。
方法:全部继承Collection中的方法。
set测试类
package com.jiateng.collection.Set;import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class Demo01 { public static void main(String[] args) { Set set=new HashSet<>(); //添加 set.add("小米"); set.add("苹果"); set.add("华为"); System.out.println(set.toString());//无序 //删除// set.remove("小米");// set.clear();// System.out.println(set.size()); //遍历 System.out.println("_________增强for____________-"); for (String s :set){ System.out.println(s); } System.out.println("----------迭代器-------"); Iterator iterator = set.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } //判断 System.out.println(set.contains("华为")); System.out.println(set.isEmpty()); }}
HashSet
HashSet是基于HashMap:构造器是new了一个HashMap、add方法是调用put方法
基于HashCode实现元素不重复。
当存入元素的哈希码相同时,会调用equals方法进行确认。结果为true时拒绝进入。
package com.jiateng.collection.Set;import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class Demo01 { public static void main(String[] args) { HashSet set=new HashSet<>(); //添加 set.add("小米"); set.add("苹果"); set.add("华为"); System.out.println(set.toString());//无序 //删除// set.remove("小米");// set.clear();// System.out.println(set.size()); //遍历 System.out.println("_________增强for____________-"); for (String s :set){ System.out.println(s); } System.out.println("----------迭代器-------"); Iterator iterator = set.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } //判断 System.out.println(set.contains("华为")); System.out.println(set.isEmpty()); }}
重写hashCode与equals&&存储过程
package com.jiateng.collection.Set;import java.util.Collection;import java.util.HashSet;import java.util.Iterator;import java.util.Objects;public class Demo02 { public static void main(String[] args) { HashSet hash = new HashSet(); Person p1= new Person("梁朝伟",20); Person p2= new Person("郭富城",21); Person p3= new Person("张佳腾",22); Person p4= new Person("吴彦祖",23); //添加 hash.add(p1); hash.add(p2); hash.add(p3); hash.add(p4);//相同元素添加不进去 hash.add(new Person("梁朝伟",20)); System.out.println("元素的个数为:"+hash.size()); System.out.println(hash); //删除// hash.remove(new Person("梁朝伟",20)); //此时能够删除。原因:我重写了hashCode与equals方法 //如果对象的name与age相同,那么hashCode方法将会返回相同的存储地址。 //重写equals方法将会判断两个对象相同。此时可以删掉 System.out.println(hash.size()); //遍历 System.out.println("__________增强for___________"); for (Person person : hash) { System.out.println(person); } System.out.println("____________迭代器________"); Iterator it = hash.iterator(); while(it.hasNext()){ System.out.println(it.next()); } //判断 System.out.println(hash.contains(new Person("梁朝伟", 20))); System.out.println(hash.isEmpty()); }}class Person{ //属性 public String name; public int age; //构造器 public Person(String name ,int age){ this.name=name; this.age=age; } //get set 方法 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; } //重写toString方法 @Override public String toString() { return "Person{" + "name='" + name + ''' + ", 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() { return Objects.hash(name, age); }}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tT6FaWkm-1635068326805)(D:学习截图捕获.PNG)]
TreeSet
存储:红黑树
TreeSet依赖于TreeMap实现
TreeSet第一种实现方法,利用元素实现Comparable
package com.jiateng.collection.Set;import java.util.Iterator;import java.util.TreeSet;public class Dem03{ public static void main(String[] args) { TreeSet treeSet = new TreeSet<>(); Person p1=new Person("刘德华",29); Person p2=new Person("成龙",22); Person p3=new Person("周星驰",24); //添加 treeSet.add(p1); treeSet.add(p2); treeSet.add(p3); treeSet.add(new Person("成龙",22)); System.out.println(treeSet.size());//抛出异常ClassCastException原因:元素没有实现Comparable //删除// treeSet.remove(new Person("成龙",22));// System.out.println(treeSet.size()); //遍历 System.out.println("_________增强for________"); for (Person person : treeSet) { System.out.println(person); } System.out.println("_________迭代器________"); Iterator iterator = treeSet.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } //判断 System.out.println(treeSet.contains(new Person("成龙", 22))); }}
TreeSet第二种实现方法,利用含参构造Comparator
package com.jiateng.collection.Set;import java.util.Comparator;import java.util.TreeSet;public class Demo04 { public static void main(String[] args) { //利用匿名内部类,实现自定义比较规则。 TreeSet treeSet =new TreeSet(new Comparator() { @Override public int compare(Person o1, Person o2) { int n1= o1.age-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("王五", 22); //添加 treeSet.add(p1); treeSet.add(p2); treeSet.add(p3); System.out.println(treeSet.toString()); }}
案例
package com.jiateng.collection.Set;import java.util.Comparator;import java.util.TreeSet;public class Text { public static void main(String[] args) { //无参构造 匿名内部类 实现定制比较规则 TreeSet treeSet = new TreeSet(new Comparator(){ @Override public int compare(String o1, String o2) { //长度不同按长度比较,相同按原先的规则比较。 int n1=o1.length()-o2.length(); int n2=o1.compareTo(o2); return n1==0?n2:n1; } }); String j0= new String("jdi"); String j1 = new String("jsojnxxzzjdi"); String j2 = new String("skdofzlm"); String j3 = new String("j"); //添加 treeSet.add(j0); treeSet.add(j1); treeSet.add(j2); treeSet.add(j3); System.out.println("元素个数为:"+treeSet.size()); System.out.println(treeSet.toString()); }}
Map
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b9qq7FkO-1635068326810)(D:学习截图9.11.PNG)]
Map接口的使用
package com.jiateng.Map;import java.util.HashMap;import java.util.Map;import java.util.Set;public class Demo01 { public static void main(String[] args) { Map map = new HashMap<>(); //让(添加) map.put("cn","中国"); map.put("uk","英国"); map.put("usa","美国"); map.put("usa","jia");//键不可以重复,但新键会把老键替换掉。 System.out.println(map.toString()); System.out.println(map.size()); //删除// map.remove("uk");// System.out.println(map.toString()); /public class Demo03 { public static void main(String[] args) { //红黑树需要设置比较规则 利用Comparator或者Comparable TreeMap treeMap = new TreeMap<>(new Comparator() { @Override public int compare(Studente o1, Studente o2) { int n1=o1.age-o2.age; //此处规则只有年龄比较,所以往后添加、删除、等是否可以都是以年龄判断 return n1; } }); Studente s1 = new Studente("孙悟空", 20); Studente s2 = new Studente("猪八戒", 21); Studente s3= new Studente("沙悟净", 22); //添加(让) treeMap.put(s1,"石头"); treeMap.put(s2,"高老庄"); treeMap.put(s3,"流沙河"); System.out.println(treeMap); System.out.println(treeMap.size()); //删除 treeMap.remove(s1); System.out.println(treeMap.size()); //遍历 System.out.println("____keySet________"); for (Studente studente : treeMap.keySet()) { System.out.println(studente+"-----"+treeMap.get(studente)); } System.out.println("____entrySet________"); for (Map.Entry studenteStringEntry : treeMap.entrySet()) { System.out.println(studenteStringEntry); } }}
Collections工具类
package com.jiateng.collection;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;public class Demo03 { public static void main(String[] args) { List objects = new ArrayList<>(); objects.add(90); objects.add(334); objects.add(1); objects.add(9); objects.add(54); //1.sort排序 System.out.println("排序前"); System.out.println(objects); Collections.sort(objects); System.out.println("排序后"); System.out.println(objects); //2.binarySearch二分查找 前提:有序 System.out.println(Collections.binarySearch(objects, 1)); //3.copy复制 注意:这里两个数组的长度必须相同才可以复制,否则抛出异常:IndexOutOfBoundsException List objects1 = new ArrayList<>(); for (int i = 0; i < objects.size(); i++) { objects1.add(0); } Collections.copy(objects1,objects); System.out.println(objects1); //reverse反转 Collections.reverse(objects); System.out.println(objects); //shuffle打乱 Collections.shuffle(objects); System.out.println(objects); //补充List转成数组 Integer[] integers = objects.toArray(new Integer[0]); //集合转成List String[] s1={"jiateng","2222","666","wyf"}; //注意这里数组转成集合后,集合的长度不可以在改变。 System.out.println("------------------"); List objects2 = Arrays.asList(s1); System.out.println(objects2.toString()); Integer[] n1={32,32,34,34,35,4};//这里注意:基本类型不可以进入集合,需要包装类。 List ints = (List) Arrays.asList(n1); }}
Collection总结
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pcnWgnYN-1635068326822)(D:学习截图9.12.8.PNG)]



