文章目录
集合框架Collection
什么是集合
集合不能存储基本类型(自动装箱)
- 对象的容器,实现了对对象的常用操作,类似数组功能。
- 集合与数组的区别
数组长度固定,集合长度不固定
数组可以存储基本类型与引用类型,集合只能存放引用类型
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yVGHdufT-1635068326792)(D:\学习截图\2191.PNG)]
collection的使用(1)ArrayList
package com.jiateng.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
*
* @author jiateng
* */
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.*;
/**
* List子接口的使用
* 特点1.有序 2.可以重复
* @author jiateng
* */
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.size();i++){
System.out.println(list.get(i));//get方法可以获取脚标对应的元素;indexOf方法可以输入元素获得脚标。
}
System.out.println("_________3.2 增强for循环遍历______");
for (Object o : list) {
System.out.println(o);
}
System.out.println("_________3.3 Iterator循环遍历______");
Iterator iterator= list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("+++++++++3.4使用列表迭代器++++++++++");
//列表迭代器与迭代器的区别:可以前后遍历,添加、删除、修改元素。还可以获取元素下标。
ListIterator lis = list.listIterator();
while(lis.hasNext()){//从前往后遍历
System.out.println(lis.nextIndex()+":"+lis.next());/*注意:若要从后往前遍历,
需要先从前往后遍历。原因:指针默认指向最前段。
*/
}
while(lis.hasPrevious()){//previous()与next()同时调用会重复返回同一个元素
/*previous()获取前一个元素,指针前移;同时next()方法获取下一个元素且指针后移;如此同时调用
两种方法会进入死循环,调用同一个元素。
*/
System.out.println(lis.previousIndex()+":"+lis.previous());
}
//4.判断
System.out.println("___________判断___________");
System.out.println(list.contains("苹果"));//是否存在
System.out.println(list.isEmpty());//是否为空
//5.获取元素下标的位置
System.out.println(list.indexOf("华为"));
}
}
List实现类
ArrarList内部是数组实现
package com.jiateng.collection.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ListIterator;
/**
* ArrayList的使用(实际上是个数组)
*
*
* */
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));/*用脚标可以删除;
当传输为一个对象时,实际上使用equals方法比较。如果想输入内容也可以移除时可以重写equals方法。*/
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;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; //存放元素的数组(下称数组)
// non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
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;
/**
* 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;
/**
* LinkedList的使用
* 特点:双向链表
*
*
* */
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;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first; //头指针
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last; //尾指针
/**
* Constructs an empty list.
*/
public LinkedList() { //无参构造
}
=================================================================================
public boolean add(E e) {
linkLast(e);
return true;
}
=================================================================================
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
=================================================================================
private static class Node<E> {
E item; //item存放数据
Node<E> next; //类似于指针域
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
Node类结点 item存放元素
泛型
泛型:java泛型是jdk1.5中引入的一个新特性,其本质是参数化类型,吧类型作为参数传递。
常见形式有泛型类、泛型接口、泛型方法。
语法<T,…>T称位类型占位符,表示一种引用类型。
E - Element (在集合中使用,因为集合中存放的是元素)
T - Type(Java 类)
K - Key(键)
V - Value(值)
N - Number(数值类型)
? - 表示不确定的java类型
好处:
- 提高代码的重用性
- 防止类型转化异常,提高代码的安全性
泛型类
package com.jiateng.collection.List;/** * 泛型类 * 语法:类名<T> * T:类型占位符 * * @author jiateng * */public class Demo06<T> { //注意:泛型可以创建变量,但是不可以实例化。 //原因:泛型传递的类型中构造方法的私有性不确定。 //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<String> s = new Demo06<String>(); s.t="Holle"; s.say("你好加油!"); Demo06<Integer> in= new Demo06<>(); in.t=1000; in.say(800); Integer t = in.getT(); System.out.println(t); }}
泛型接口
package com.jiateng.collection.List;/** * 泛型接口 * 语法:接口名<T> *注意:在接口内不可以定义泛型变量,因为在接口内属性的定义为 public static final * 由于static的特性,泛型的类型不能被确定。 * @author jiateng * */public interface Demo08<T> {String name="ji";T say(T t);}
package com.jiateng.collection.List;public class MyInterfacempl implements Demo08<String>{//1.此处的占位符必须是类型 public MyInterfacempl(){ } @Override public String say(String t) { System.out.println(t); return t; }}
package com.jiateng.collection.List;public class MyIntegerfacempl<T> implements Demo08<T>{//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<Integer> inte = new MyIntegerfacempl<>(); inte.say(9882); }}
泛型方法
package com.jiateng.collection.List;/** * 泛型方法 * 语法: * 修饰符 <T> Type 方法名() * * */public class Demo09 { int a; //泛型方法 public <T> 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<String> obj = new LinkedList<String>(); 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;/** * Set测试类 * 特点:无序、无下标、元素不可以重复 * * */public class Demo01 { public static void main(String[] args) { Set<String> 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<String> 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;/** * Set实现类 * HashSet * 存储结构:哈希表(数组、链表、红黑树)红黑树在8之后 * 特点:无序、无下标、元素不可以重复 * * */public class Demo01 { public static void main(String[] args) { HashSet<String> 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<String> 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;/** * Set的实现类 * HashSet * 存储过程: * 1.根据hashcode计算保存的位置,若此位置为空则保存,否则执行第二步 * 2.根据equals判断,若为true,则认为是重复,拒绝添加。否则在此处形成链表。 * * @author jiateng * */public class Demo02 { public static void main(String[] args) { HashSet<Person> hash = new HashSet<Person>(); 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));/*此时可以添加成功,因为此处没有重写equals方法, equals判断为false,形成链表。 */ 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<Person> 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;/** * set实现类 * TreeSet * 存储结构:红黑树 * 元素必须实现Comparable接口,CompareTo()方法返回值为零则认为是重复元素 * * @author jiateng * */public class Dem03{ public static void main(String[] args) { TreeSet<Person> 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<Person> 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;/** * TreeSet实现类 * 利用含参构造Cmoparator * @author jiateng * */public class Demo04 { public static void main(String[] args) { //利用匿名内部类,实现自定义比较规则。 TreeSet<Person> treeSet =new TreeSet<Person>(new Comparator<Person>() { @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;/** * 案例 * 要求:利用TreeSet集合实现存储String类型的元素,并按元素的长短存储。 * * * @author jiateng * */public class Text { public static void main(String[] args) { //无参构造 匿名内部类 实现定制比较规则 TreeSet<String> treeSet = new TreeSet<String>(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; } }); 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;/** * 实现Map接口 * 特点:1.存储键值对 2.键不可以重复值可以 3.无序 * * * @author jiateng * */public class Demo01 { public static void main(String[] args) { Map<String, String> 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()); //****遍历**** //1.使用keySet System.out.println("1.使用keySet"); //注意:keySet返回值是一个Set类型。因此就可以使用迭代器与增强forle for (String key : map.keySet()) { System.out.println(key+"----"+map.get(key)); } //2.使用entrySet System.out.println("2.使用entrySet"); Set<Map.Entry<String,String>> entrySets=map.entrySet(); //Entry是Map接口下的一个接口,存放的是键值对。 for (Map.Entry<String, String> entrySet : entrySets) { System.out.println(entrySet); //或者System.out.println(entrySet.getKey()+"----"+entrySet.getValue()); } }}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8rNKSEcK-1635068326818)(D:\学习截图\9.11.19.11.PNG)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2XwA2gJF-1635068326820)(D:\学习截图\9.11.20.PNG)]
HashMap
无参构造:构造一个具有默认初始容量16,和默认加载因子0.75(当容量到达75%时扩容)
先是数组进行存放,如果元素由HashCode计算的地址不为空,且equals判断为true,此时在此形成链表,当链表长度大于8且数组长度大于64时,链表转制成红黑树(查找效率高),当小于6时红黑树转回链表。
源码分析总结
- HashMap刚创建时,table(存放元素的数组)为null,size为0,为了节省空间,当添加第一个元素时,table容量调整为16。
- 当元素个数大于阈值时(16*0.75=12)时会进行扩容,扩容后大小为原来的2倍,目的是减少调整元素的个数。
- jdk8当链表长度大于8,并且数组长度大于等于64时,链表会调整为红黑树,提高执行效率
- jdk8当链表长度小于6时,红黑树调整为链表
- jdk8以前,链表是前插法,jdk8后是尾插法。
Hashtable
子类:Properties类表示了一个持久的属性集。properties可保存在流中或从流中加载。
TreeMap
package com.jiateng.Map;import java.util.Comparator;import java.util.Map;import java.util.TreeMap;/** * Map实现类 * TreeMap * 存储结构:红黑树 * * @author jiateng */public class Demo03 { public static void main(String[] args) { //红黑树需要设置比较规则 利用Comparator或者Comparable TreeMap<Studente, String> treeMap = new TreeMap<>(new Comparator<Studente>() { @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<Studente, String> 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;/** * Collections工具类 * * * * @author jiateng */public class Demo03 { public static void main(String[] args) { List<Integer> 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<Integer> 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<String> objects2 = Arrays.asList(s1); System.out.println(objects2.toString()); Integer[] n1={32,32,34,34,35,4};//这里注意:基本类型不可以进入集合,需要包装类。 List<Integer[]> ints = (List<Integer[]>) Arrays.asList(n1); }}
Collection总结
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pcnWgnYN-1635068326822)(D:\学习截图\9.12.8.PNG)]