一,java语言概述

1.常用Dos命令

  1. dir:列出当前目录下的文件以及文件夹
  2. md:创建目录
  3. rd:删除目录(空目录)
  4. cd:进入指定目录
  5. cd..:退回上一级目录
  6. cd/:退回根目录
  7. del:删除文件
  8. echo 1 >java.txt:创建文件
  9. exit:退出

2,java语言运行机制及运行过程

  1. Java语言特点:跨平台性
  2. Java两种核心机制:
  3. Java虚拟机(jvm):Java程序运行环境
  4. 垃圾回收机制(gc)

3.jdk,jre,jvm的关系

  1. jdk:Java开发工具包。(Java开发工具包和jre)
  2. jre:Java运行环境。(包括jvm)

4 环境变量的配置

  1. 为什么要添加环境变量?
  2. 让Java工具包在任何路径下都可以使用。
  3. 高级系统设置-环境变量:
  4. 系统变量-path(window系统执行命令时需要搜索的路径)
  5. 加上 jdk的安装路径\bin
  6. 开发时的配置(推荐):
  7. 在系统变量里面新建变量JAVA_HOME 值为jdk安装路径。
  8. 然后再classpath变量中加入:%JAVA_HOME%\bin

5.HelloWorld

  1. 如何显示记事本后缀:
  2. 我的电脑-查看-文件拓展名
  3. Java代码写在.java结尾的文件中。(源文件)
  4. 通过javac命令对该Java文件进行编译。(字节码文件)
  5. 通过Java命令对。class文件进行运行。

6 注释

  1. 1.单行注释//
  2. 2.多行注释/**/
  3. 3.文档注释/** */
  4. 注释内容可以被jdk提供的工具javadoc解析,生成一套以网页文件形式体现的该程序的说明文档。

二,java基本语法

1.关键字和保留字

  1. 关键字:在Java语言里有特殊含义的字符串。
  2. 保留字:目前没用到,以后的版本可能会用到。

2.标识符

  1. 标识符:自己起的名字。包括:包名,类名。。。
  2. 0-9 _ $
  3. 数字不可以开头
  4. 不能使用关键字和保留字,可以包含
  5. 严格区分大小写
  6. 不能包含空格

3.变量

  1. 变量
  2. 变量:内存中的一个存储区域。
  3. 可以在同一类型范围内变化。
  4. 包含:类型,名,存储的值。
  5. 作用:内存中保存数据。
  6. 先声明,后使用。
  7. 同一个作用域内,不能定义重复的变量名。
  8. 变量分类:按照数据类型分类
  9. 基本数据类型:数值(整数,浮点数),字符,布尔
  10. 引用数据类型:类(包括字符串),接口,数组
  11. 变量分类:按照声明位置不同分类
  12. 成员变量:(类内,方法体外)
  13. 包括:实例变量(不以static修饰),类变量(以static修饰)
  14. 局部变量:(方法体内)
  15. 包括:形参,方法局部变量,代码块局部变量
  16. 1.整型:byte,short,int,long 字节(1.2.4.8)1字节=8bit
  17. *long型变量的声明必须以l或L结尾
  18. 2.浮点型:float(4),double(8)
  19. float:单精度浮点数,精确7位
  20. *Java的浮点型常量默认为double类型,声明float常量,后加f或F。
  21. 3.字符类型 char(2)
  22. 表示方式:1.声明一个字符,2.定义一个转义符。
  23. char c='\n';
  24. 4.布尔类型
  25. boolean:true,false
  26. 双引号里面如果想要使用双引号,前面需要加\
  27. char+int=int
  28. 基本数据类型之间的运算
  29. 1.自动类型提升
  30. byte+int=int
  31. Java支持自动向上转型。
  32. 当byte,char,short三种变量做运算时,结果为int。
  33. 2.强制类型转换
  34. 向下转型
  35. 强制类型转换符(int),可能会损失精度。
  36. *long赋值的数后面不加l可能会导致编译失败,过大的整数。
  37. 整型常量默认类型为int,浮点型默认常量为double。
  38. String类型变量的使用
  39. String属于引用类型。
  40. String可以和所有类型做运算。

4.运算符

  1. 算术运算符
  2. a=2;b=++a;=>a=3,b=3;
  3. a=2;b=a++;=>a=3,b=2;
  4. 赋值运算符
  5. 比较运算符
  6. 逻辑运算符
  7. &和&&的异同:
  8. 1)都表示且
  9. 2)&&短路且
  10. 位运算符
  11. 三元运算符
  12. 三元运算符的嵌套:
  13. int sum=(a>b):a?((a==b)?"a==b":b)
  14. 另一个三目运算符作为表达式出现

5.流程控制

  1. 顺序结构
  2. 分支结构
  3. if-else
  4. switch-case
  5. switch(表达式){
  6. case 常量1:
  7. 执行语句;
  8. break;
  9. default:
  10. 执行语句;
  11. }
  12. switch结构中的表达式,只能是如下6种数据类型:
  13. byte,short,char,int,String,枚举。
  14. 例题:年份累加
  15. 循环结构:
  16. for
  17. while
  18. do{
  19. }while();
  20. 键盘输入:
  21. import java.util.Scanner;
  22. Scanner sc=new Scanner(System.in);
  23. int a=sc.nextInt();
  24. String b=sc.next();

三,数组

1.一维数组

1)数组默认值

  1. 数组元素的默认初始化值:
  2. 整型数组元素默认值为0
  3. 浮点型数组元素默认值0.0
  4. 布尔型数组元素默认值false
  5. 字符型数组元素默认值Ascii值位0的元素
  6. 引用数据类型数组元素默认值null

2)一位数组内存解析

JAVA-SE核心基础篇 - 图1

JAVA-SE核心基础篇 - 图2


2.二维数组

1)二维数组的使用

  1. // 静态初始化
  2. int[][] arr = new int[][] { { 1, 2, 3 }, { 4, 5 }, { 6, 8, 7 } };
  3. // 动态初始化1
  4. int[][] arr1 = new int[3][2];
  5. // 动态初始化2
  6. int[][] arr2 = new int[3][];
  7. // 调用arr2
  8. arr2[1] = new int[3];// 先指定列的个数
  9. for (int i = 0; i < arr2[1].length; i++) {
  10. System.out.println(arr2[1][i]);
  11. }
  12. // 如何获取数组的长度
  13. System.out.println(arr.length);// 3
  14. System.out.println(arr[0].length);// 3
  15. // 二维数组元素的调用
  16. for (int i = 0; i < arr.length; i++) {
  17. for (int j = 0; j < arr[i].length; j++) {
  18. System.out.println(arr[i][j]);
  19. }
  20. }

2)二维数组默认初始值

  1. int a[][]=new int[3][3];
  2. System.out.println(a[0]);//输出地址[I@15db9742
  3. System.out.println(a[0][0]);//0
  4. System.out.println(a[2][3]);//java.lang.ArrayIndexOutOfBoundsException

3)二维数组的内存解析

JAVA-SE核心基础篇 - 图3

3.数组中设计的常见算法:

1)反转

2)线性查找

3)二分查找

4)冒泡排序

4.Arrays工具类的使用

  1. Arrays工具类的使用
  2. int a[] = new int[] { 43, 26, 25, 65, 89, 75, 45, 13, 23, 15, 65 };
  3. int b[] = new int[] { 43, 26, 25, 65, 89, 75, 45, 13, 23, 15, 65 };
  4. System.out.println(Arrays.equals(a, b));//判断两个数组是否相等
  5. Arrays.sort(a);//对数组进行从小到大排序
  6. int key=89;
  7. System.out.println(Arrays.binarySearch(a, key));//对排序后的数组进行二分查找
  8. System.out.println(Arrays.toString(a));//输出数组信息

5.数组中的常见异常

  1. 1.下标越界异常
  2. 2.空指针异常
  3. /*
  4. * int a[] = new int[] { 43, 26, 25, 65, 89, 75, 45, 13, 23, 15, 65 }; a=null;
  5. * System.out.println(a[0]);
  6. */
  7. /*
  8. * int[][]arr=new int [4][];
  9. * System.out.println(arr[0][0]);
  10. */
  11. String arr[]=new String [] {"aa","bb","cc"};
  12. arr[0]=null;
  13. System.out.println(arr[0].toString());

四,面向对象

1.成员变量(属性)与局部变量的区别

  1. 不同点:
  2. 1.类中的声明位置不同
  3. 1)类内,方法体外
  4. 2)方法的形参列表,方法体内,构造器形参,构造器内部变量
  5. 2.权限修饰符的不同
  6. 1)可以在声明属性时指明其权限,使用权限修饰符
  7. 2)不能使用权限修饰符
  8. 3.默认初始化值
  9. 1)根据其类型都有默认的初始化值
  10. 2)没有默认初始化值(调用之前显示赋值),形参在调用时赋值。
  11. 4.内存中加载的位置
  12. 1)堆中(非static)
  13. 2)栈中

2.return关键字

  1. 1适用范围:使用在方法体中
  2. 2.作用:
  3. 1)结束方法
  4. 2)针对有返回值类型的方法,返回值。
  5. 3.return 后面不可以声明执行语句
  6. 方法中使用的注意点:
  7. 可以调用当前类的属性和方法
  8. 方法中不可以定义方法

3.对象数组

内存解析

JAVA-SE核心基础篇 - 图4

4.匿名对象与方法重载

匿名对象

  1. new Phone().price=1999;
  2. new Phone().showPrice;//0.0
  3. 每次new的都是堆空间的一个新对象。

方法重载

  1. 1.定义:在同一个类中,允许存在一个以上同名方法,
  2. 只要他们的参数个数/顺序,参数类型不同即可。
  3. 2.特点:与返回值无关,与权限修饰符无关。
  4. 常见的:构造器重载

5.可变个数形参与变量赋值

可变个数形参

  1. Object...args
  2. 如果有多个参数,必须放到最后。

变量赋值

  1. 如果变量是基本数据类型:此时赋值的是变量所保存的数据值。
  2. 如果变量时引用数据类型:此时赋值的是变量所保存数据的地址值。
  3. 此时改变变量的值,相当于改变地址对应的值。

6.值传递机制与递归方法

值传递机制

  1. 形参:方法定义时,小括号内的参数。
  2. 实参:方法调用时,实际传递给形参的值。
  3. 如果参数是基本数据类型,此时赋值的是变量所保存的数据值。
  4. 如果参数是引用数据类型,此时赋给形参的值,是变量所指向地址的值。

递归方法

一个方法体内,自己调用自己。

  1. /**
  2. * 递归方法求1-100的和
  3. */
  4. public static void main(String[] args) {
  5. int n = 100;
  6. int sum = getSum(n);
  7. System.out.println(sum);
  8. }
  9. public static int getSum(int sum) {
  10. if (sum == 1) {
  11. return 1;
  12. } else {
  13. return sum + getSum(sum - 1);
  14. }
  15. }
  16. /**
  17. * 已知一个数列,f(0)=1,f(1)=4,f(n+2)=2*f(n+1)+f(n);
  18. * 其中n是大于0的整数,求f(10。
  19. *
  20. * @param sum
  21. * @return
  22. */
  23. public static int getSum(int sum) {
  24. if (sum == 0) {
  25. return 1;
  26. } else if (sum == 1) {
  27. return 4;
  28. } else {
  29. return 2 * getSum(sum - 1) + getSum(sum - 2);
  30. }
  31. }
  32. /**
  33. * 递归方法求斐波那契数列的前n项,并输出。
  34. * @return
  35. */
  36. public static void main(String[] args) {
  37. int arg=10;
  38. int avg=getArgs(arg);
  39. System.out.println(avg);
  40. }
  41. public static int getArgs(int args){
  42. if(args<=2){
  43. return 1;
  44. }
  45. else{
  46. return getArgs(args-1)+getArgs(args-2);
  47. }
  48. }

7.封装和隐藏

封装和隐藏:

  1. 特点:
  2. 高内聚:类的内部数据操作细节自己完成,不允许外部干涉
  3. 低耦合:仅仅对外暴漏少量方法用于使用。
  4. 体现:私有化属性,设置公有的方法来获取和设置属性。需要权限修饰符来配合。

权限修饰符:

  1. 1.private:类内部
  2. 2.default:同一包下的类
  3. 3.protected:不同包的子类
  4. 4.public:同一项目下
  5. 用来修饰类:public和default,和类的内部结构:属性,方法,构造器,内部类。

构造器:construct

  1. 作用:
  2. 1)创建对象
  3. 2)初始化对象
  4. 构造器重载

属性赋值的先后顺序:

  1. 1)默认初始化
  2. 2)显示初始化
  3. 3)构造器初始化
  4. 4)set方法

javabean

  1. 类是公有的
  2. 有一个无参的公共构造器
  3. 有属性,且有对应的get,set方法

关键字this的使用

  1. 1)this可以用来修饰属性和方法
  2. this代表当前对象
  3. 2)this可以用来修饰和调用构造器
  4. 调用构造器:
  5. public Student(Integer number, Integer state) {
  6. this.number = number;
  7. this.state = state;
  8. }
  9. public Student(Integer number, Integer state, Double score) {
  10. this(number,state);//调用其他构造器,不能调用自己。
  11. this.score = score;
  12. }

MVC设计模式:

  1. 视图模型层view
  2. 控制器层controller:service,base,activity
  3. 模型层model:bean,dao,db

继承性:extends

  1. 减少了代码的量,提高了代码复用性
  2. 便于功能的拓展
  3. 为多态的实现提供了前提
  4. 一旦子类A继承父类B以后,A就获取了B中声明的所有属性和方法。
  5. 规定:
  6. 一个类可以被多个子类继承
  7. 一个类只能由一个父类
  8. 允许多层继承

8.Eclipse中的Debug

  1. Debug:
  2. 1.设置断点:
  3. 2.按键:
  4. F5进入方法,F6一行一行执行,F7从方法中出来
  5. resume:终止此处断点,进入下一处。
  6. Terminate:强行终止
  7. debug中step into功能失灵问题:更换eclipsejre为jdk的。

9.方法重写与权限修饰符

方法重写

  1. 1.重写:子类继承父类以后,可以对父类中同名同参数的方法,进行覆盖操作。
  2. 2.应用:重写以后,当子类执行该方法,实际上执行的是子类重写父类的方法。
  3. 3.规定:
  4. 方法名形参列表必须相同,
  5. 子类重写方法的权限修饰符不小于父类被重写的方法,
  6. *子类不能重写父类的私有方法,
  7. 返回值类型:void--》void,其他的小于等于父类的返回值类型。
  8. 子类抛出的异常类型不能大于父类。
  9. 非static(因为静态方法不能被覆盖,随着类的加载而加载)

权限修饰符

  1. 四种权限修饰符
  2. 在不同包的子类中,能调用order类中声明为protected和public的属性,方法。
  3. 不同包下的不同类(非子类)只能调用order类中的public的属性和方法。

10.super关键字

  1. super调用属性和方法
  2. 1.我们可以在子类的方法或构造器中,通过使用"super."属性/方法的方式,显示的调用
  3. 父类中声明的属性或方法,通常省略。
  4. 2.特殊情况下,当子类和父类定义了同名的属性时,用super来调用父类的方法。
  5. 3.当子类重写了父类的方法,在子类的方法中调用父类中被重写的方法,必须使用super。
  6. 4.super调用构造器:
  7. public Student(int id,String name,String school){
  8. super(id,name);//调用父类的构造器
  9. this.school=school;
  10. }
  11. 在子类构造器中用super(形参列表)调用父类中声明的指定的构造器。
  12. super声明在子类构造器首行。

11.子类对象实例化全过程:

  1. 1.从结果上看,
  2. 子类继承父类以后,就获取了父类中声明的属性和方法;
  3. 创建子类对象,在堆空间中,就会加载所有父类中声明的属性。
  4. 2.从过程上看,
  5. 当我们通过子类的构造器创建子类对象时,我们一定会直接或间接地调用其父类构造器,
  6. 进而调用父类的父类的构造器,知道调用了Object的无参构造器为止。正因为加载过所
  7. 有的父类结构,所以才可以看到内存中有父类的结构,子类对象才可以进行调用。

12.向下转型

  1. 向下转型:使用强制类型转换符
  2. Person p=new Student();//此时p并不能调用Student中重写的方法。
  3. Student stu=(Student)p;//此时就可以了

13.instanceof关键字:

  1. stu instanceof p:
  2. 判断对象stu是否是类p的实例,如果是,返回true,如果不是,返回false。
  3. 使用情景:为了避免向下转型时出现类型转换异常,我们在向下转型之前,先用
  4. instanceof进行判断,如果返回true在进行转型。

14.java.lang.Object

  1. 1.Object类时左右Java类的父类
  2. 2.如果在声明类时没有指明类的直接父类,默认类的父类为Object。
  3. 3.Object类中的功能(属性,方法)具有通用性。
  4. 属性:无。
  5. 方法:equals()/toString()/getClass()/hashCode()/clone()克隆/finalize()垃圾回收
  6. 4.Object类只声明了一个空参构造器

15.==和equals()的区别

  1. 1.==可以使用在基本数据类型和引用数据类型变量中
  2. 2.==如果比较基本数据类型变量,比较的是数据是否相等(不一定类型要相同)。
  3. 如果比较引用类型变量,比较的是地址值是否相等,即两个对象是否指向同一个对象实体。
  4. 1.equals()是一个方法,不是运算符。
  5. 2.只适用引用数据类型。
  6. 3.Object类中equals的定义:
  7. public boolean equals(Object obj) {
  8. return (this == obj);
  9. }
  10. String类中定义的equals方法:
  11. STring对equals方法进行了重写,如果地址相同,返回true,
  12. 否则比较字符串的值是否相同。

16.equals()方法的重写:

  1. public boolean equals(Object o) {
  2. if (this == o) return true;
  3. if (o == null || getClass() != o.getClass()) return false;
  4. Customer customer = (Customer) o;
  5. return age == customer.age &&
  6. Objects.equals(name, customer.name);
  7. }

17.Object类中toString()的使用:

  1. 1.当我们输出一个对象的引用,实际上就是调用当前对象的toString()
  2. 2.Object类中对toString()的定义:
  3. public String toString() {
  4. return getClass().getName() + "@" + Integer.toHexString(hashCode());
  5. }
  6. 3.向String,Date,File。包装类实际上都重写了Object的toString方法。
  7. 使得在调用对象的toString方法时,返回实体对象信息。
  8. 4.自定义类重写toString方法

18.包装类

八种数据类型都有对应的包装类
char—>Character

  1. public static void main(String[] args) {
  2. /**
  3. * 基本数据类型和包装类,String的转换
  4. * jdk5.0新特性:自动拆箱与自动装箱
  5. */
  6. //包装类转换为基本数据类型
  7. Integer a=10;
  8. int b=a;//自动拆箱
  9. int c=a.intValue();//int->integer
  10. //基本数据类型转换为包装类
  11. int num1=10;
  12. Integer num2=num1;//自动装箱
  13. Integer num3=new Integer(num1); //integer->int
  14. //基本数据类型和包装类与String的转换
  15. int num=1;
  16. String s1=num+"";//int->String
  17. String s2=String.valueOf(num);//int->String
  18. Integer number=10;
  19. String s3=String.valueOf(number);//integer->String
  20. int aa=Integer.parseInt(s3);//String->int
  21. Integer bb= Integer.parseInt(s3);//String->integer
  22. }
  1. /**
  2. * 面试题:
  3. * 三目运算符后面两个条件语句对应的类型会在比较前进行统一。
  4. */
  5. Object o1=true?new Integer(1):new Double(2.0);
  6. System.out.println(o1);//1.0

Integer内部存在一个Integer[]数组,范围-128—+127,如果我们是用自动装箱的方式,
给integer赋值的范围在此范围内直接从数组中取。

19.static关键字

  1. 1.可以用来修饰属性,方法,代码块,内部类
  2. 2.修饰属性:
  3. 静态属性(类变量)和非静态属性(实例变量)
  4. 实例变量:每个对象都有自己的实例变量。
  5. 静态变量:所有对象共享静态变量。通过一个对象修改,别的对象调用的也是修改过的。
  6. public static void setCountry(String country) {
  7. Chinese.country = country;
  8. }
  9. 静态变量随着类的加载而加载。
  10. 静态变量的加载早于对象的创建。
  11. 由于类只会加载一次,则静态变量在内存中也只存在一份,在方法区的静态域中。
  12. 3.修饰方法:
  13. 静态方法_随着类的加载而加载。
  14. 静态方法中只能调用静态的方法或属性。
  15. 非静态方法中,既可以调用非静态的方法或属性,也可以调用静态的方法或属性。
  16. 4.开发中如何确定一个属性要声明为static?
  17. 所有对象都相同的属性。
  18. 开发中如何确定一个方法要声明为static?
  19. 操作静态属性的方法
  20. 工具类中的方法
  21. static实现id自增
  22. private static int idadd=1001;

类变量与实例变量的内存解析

JAVA-SE核心基础篇 - 图5

20.单例设计模式:

  1. 1.采取一定的方法,保证在整个软件系统中,对某个类只能存在一个对象实例。
  2. 2.饿汉式vs懒汉式实现:
  3. //饿汉式
  4. public class Test1 {
  5. //私有的构造器
  6. private Test1(){
  7. }
  8. //私有的创建对象
  9. private static Test1 test=new Test1();
  10. //公有的方法供外部调用
  11. public static Test1 getTest1(){
  12. return test;
  13. }
  14. }
  15. //懒汉式
  16. public class Test1 {
  17. //私有的构造器
  18. private Test1(){
  19. }
  20. //私有的创建对象
  21. private static Test1 test=null;
  22. //公有的方法供外部调用
  23. public static Test1 getTest1(){
  24. if(test==null){
  25. test=new Test1();
  26. }
  27. return test;
  28. }
  29. }
  30. 3.懒汉式和饿汉式的对比:
  31. 饿汉式占用内存,线程安全的。
  32. 懒汉式好处:延迟对象的创建,线程不安全。
  33. 4.应用场景:
  34. 网站计数器,应用程序的日志应用,数据库连接池,Application。
  35. main()方法的使用说明
  36. 也是一个普通的静态方法
  37. 可以做输入

21.代码块:和属性赋值顺序完结篇

  1. 作用:用来初始化对象。
  2. 只能用static来修饰
  3. 分类:静态代码块,非静态代码块
  4. 非静态能调用静态的属性方法,静态的不能掉用非静态的属性方法。
  5. 1.静态代码块
  6. 随着类的加载而执行
  7. 一共只执行一次,因此可以初始化类的信息。
  8. 2.非静态代码块
  9. 随着对象的创建而执行
  10. 每次创建对象都会执行一次,因此可以创建对象时初始化对象。
  1. 属性赋值顺序完结篇
  2. 1)默认初始化
  3. 2)显示初始化/在代码块中赋值
  4. 3)构造器初始化
  5. 4)set方法

22.final关键字

  1. 1.final修饰类和方法
  2. 用final修饰的类不能被继承,称为最终类。
  3. eg:String,System,StringBuffer
  4. 用final修饰的方法不能被重写。
  5. 2.final修饰变量
  6. 此时的变量就称为常量。
  7. 1)修饰属性
  8. 显式初始化,代码块中初始化。
  9. 2)修饰局部变量
  10. 该局部变量的值不能被再次修改

23.抽象类与抽象方法

  1. abstract关键字的使用
  2. 1.abstract抽象的
  3. 2.可以用来修饰的结构:类和方法
  4. 3.abstract修饰类:抽象类
  5. 1)此类不能实例化
  6. 2)抽象类中一定有构造器,便于子类实例化时调用。
  7. 3)开发中,都会提供抽象类的子类,让子类对象实例化,完成相关操作。
  8. 4.abstract修饰方法:抽象方法
  9. public abstract void test();
  10. 包含抽象方法的类一定是抽象类,抽象类不一定包含抽象方法。
  11. 如果继承了抽象类,必须继承抽象类的抽象方法。
  12. 5.注意
  13. 1)abstract不能用来修饰:属性,构造器。
  14. 2)abstract不能用来修饰私有方法,静态方法,final方法,final的类。
  15. 创建抽象类的匿名子类对象
  16. Person p=new Person(){//Person是一个抽象类
  17. public void eat(){
  18. }
  19. public void walk(){
  20. }
  21. };

24.接口:interface

  1. 1.接口的使用用interface来定义
  2. 2.Java中,接口和类是并列的两个结构。
  3. 3.如何定义接口,定义接口的成员
  4. 1)jdk7以前,只能定义全局常量和抽象方法
  5. 全局常量:public static final的,但是书写时,可以省略不写
  6. 抽象方法:public abstract的,但是书写时,可以省略不写。
  7. 2)jdk8:除了定义全局常量和抽象方法外,还可以定义静态方法,默认方法。
  8. 4.接口中不能定义构造器,接口不能实例化。
  9. 5.Java中,通过类去实现接口。implements
  10. 6.Java中允许实现多个接口。
  11. 7.接口与接口之间可以多继承
  12. 8.接口的实现体现了多态性。
  13. 面试题:接口与抽象类的比较:
  14. 1.抽象类:通过extends来继承,只能继承一个抽象类,
  15. 抽象类中一定有构造方法,创建子类对象时被调用。
  16. 抽象类中不光有抽象方法,还可以有其他方法。
  17. 2.接口:接口通过implements来实现,允许实现多个接口,
  18. 接口中不存在构造方法,接口中只能声明全局常量和抽象方法,
  19. jdk'8.0以后,还可以定义静态方法和默认方法。
  20. 3.不能实例化,都可以被继承。

接口的应用:

代理模式

  1. /**
  2. * 代理模式:将两者都要实现的行为封装在接口中,被代理对象和代理对象都继承该接口
  3. * 代理对象中声明被代理对象属性,并创建拥该属性的构造器,通过创建代理对象完成
  4. * 被代理对象的方法。
  5. */
  6. class TEST{
  7. public static void main(String[] args) {
  8. Zhuli zhuli=new Zhuli(new Star());
  9. zhuli.sing();
  10. zhuli.buyThing();
  11. zhuli.getMoney();
  12. }
  13. }
  14. public class Star implements Proxy {//被代理对象
  15. @Override
  16. public void sing() {
  17. System.out.println("明星唱歌");
  18. }
  19. @Override
  20. public void getMoney() {
  21. }
  22. @Override
  23. public void buyThing() {
  24. }
  25. }
  26. interface Proxy {
  27. public void sing();
  28. public void getMoney();
  29. public void buyThing();
  30. }
  31. class Zhuli implements Proxy{//代理对象
  32. private Star star;//声明被代理对象
  33. public Zhuli(Star star){//存在被代理对象的带参构造器
  34. this.star=star;
  35. }
  36. @Override
  37. public void sing() {
  38. star.sing();//被代理对象完成
  39. }
  40. @Override
  41. public void getMoney() {
  42. System.out.println("助理替歌手收钱");
  43. }
  44. @Override
  45. public void buyThing() {
  46. System.out.println("助理替歌手买东西");
  47. }
  48. }

工厂模式

实现创建者与调用者的分离,将创建对象的具体过程隔离起来。

  1. public interface Java8 {
  2. /**
  3. * 接口中定义的静态方法只能通过接口来调用
  4. */
  5. public static void test1(){
  6. System.out.println("***");
  7. };
  8. /**
  9. * 通过实现类的对象可以调用/重写接口中的默认方法
  10. */
  11. public default void test2(){
  12. System.out.println("***");
  13. }
  14. /**
  15. * 如果一个类继承的父类和实现的接口存在同名同参数的方法,
  16. * 子类在没有重写这个方法的前提下,默认调用父类的方法
  17. */
  18. /**
  19. * 如果一个类实现的多个接口中存在同名同参数的方法,
  20. * 子类在没有重写这个方法的前提下,会报错,接口冲突。
  21. * 如果重写的方法想要调用其中的一个:接口.super.method
  22. */
  23. }

25.内部类的使用:

1.Java中允许将一个类声明在另一个类的内部
2.内部类的分类:成员内部类(静态,非静态)vs局部内部类(方法,代码块,构造器内)
3.成员内部类:

  1. class Demo{
  2. public static void main(String[] args) {
  3. /**
  4. * 创建内部类实例
  5. */
  6. Person.Dog dog=new Person.Dog();//静态内部类
  7. Person p=new Person();//非静态内部类
  8. Person.Bird bird=p.new Bird();
  9. }
  10. }
  11. class Person {
  12. private String name;
  13. public void eat(){
  14. System.out.println("吃饭");
  15. }
  16. /**
  17. * 内部类可以被final修饰,表示此类不能被继承
  18. * 内部可以定义属性方法构造器
  19. * 可以被abstract修饰
  20. */
  21. static class Dog{
  22. //eat();不能调用外部的eat方法
  23. }
  24. class Bird{
  25. public Bird(){
  26. }
  27. /**
  28. * 调用外部成员的方法
  29. */
  30. public void sing(){
  31. eat();
  32. name="bird";
  33. }
  34. }
  35. }
  1. 面试题:创建静态内部类对象和非静态内部类对象:
  2. //静态内部类对象
  3. Person.Dog dog=new Person.Dog();
  4. //非静态内部类对象
  5. Person p=new Person();
  6. Person.Bird bird=new p.bird();

五,异常处理

1.异常的体系结构

  1. 异常:在Java中,程序执行发生的不正常情况称为异常。
  2. java.long.Throwable
  3. 1.java.long.Error,:一般不编写针对性代码进行处理
  4. 2.java.long,Exception:可以进行异常的处理
  5. 1)编译时异常:IOException,FileNotFindException,ClassNotFindException
  6. 2)运行时异常:NullPointException,ArrayIndexOutOfBoundsException,ClassCastException
  7. ,NumberFormatException,InputMismatchException,ArithmeticException

2.异常处理机制一:

  1. try-catch-finally
  2. 一旦抛出异常,其后的代码就不再执行。
  3. try {
  4. //可能会出现异常的代码
  5. } catch (异常处理类型1 变量名1) {
  6. e.printStackTrace
  7. } catch (异常处理类型2 变量名2) {
  8. e.printStackTrace
  9. } finally {
  10. //最终一定要执行的代码
  11. }
  12. 编译时异常和运行时异常的不同处理
  13. 开发时运行时异常不需要try-catch
  14. 编译时异常用try-catch来解决

3.异常处理机制二:Throws +异常类型

  1. “throws+异常类型”写在方法声明处,指明方法执行时,可能会抛出的异常。
  2. 一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,
  3. 此对象满足throws的异常类型时就会抛出,异常代码后续的代码,就不要执行。
  4. try-catch真正的将异常处理掉了,而throws只是将异常抛给了方法的调用者,并没有真正的处理掉。
  5. 重写方法异常抛出的规则
  6. 子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型
  7. 开发中如何选择try-catch还是throws
  8. 1.如果父类被重写的方法没有抛出异常,则子类重写的方法中的异常只能用try-catch
  9. 2.执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的,
  10. 我们建议这几个方法使用throws的方法进行处理,而方法a可以用try-catch进行处理。

4.手动生成一个异常对象并抛出:throw

  1. public class MyException {
  2. public static void main(String[] args) {
  3. person p=new person();
  4. try {
  5. p.setAge(-1001);
  6. } catch (Exception e) {
  7. System.out.println(e.getMessage());
  8. }
  9. }
  10. }
  11. class person {
  12. private int age;
  13. public person(){
  14. }
  15. public void setAge(int age) throws Exception{
  16. if (age>0){
  17. this.age=age;
  18. }else{
  19. throw new Exception("年龄不能小于0!");
  20. }
  21. }
  22. public int getAge(){
  23. return age;
  24. }
  25. }

5.用户自定义异常:

  1. /**
  2. * 自定义异常
  3. * 1.继承于现的异常结构,RuntimeException,Exception
  4. * 2.提供全局常量, static final long serialVersionUID
  5. * 3.提供重载的构造器
  6. */
  7. public class TestException extends IOException {
  8. static final long serialVersionUID=-7034897190745766939L;
  9. public TestException(){
  10. }
  11. public TestException(String msg){
  12. super(msg);
  13. }
  14. }

六,多线程

1.概述

1)概念

  1. 程序:为完成特定任务,用某种语言编写的一组指令的集合。
  2. 一段静态的代码,静态对象。
  3. 进程:程序的一次执行过程,或是正在运行的一个程序。
  4. 是一个动态的过程,有他本身的生命周期。
  5. 独立的方法区和堆空间
  6. 线程:一个程序内部的执行路径。
  7. 独立的计数器和栈
  1. 单核cpu和多核cpu
  2. 假的多线程,多个线程交替进行。
  3. 并行和并发
  4. 并行:多个cpu同时执行多个任务。
  5. 并发:一个cpu执行多个任务。
  6. 并行:传输的数据8位一送出去
  7. 串行:传输的数据1位1送出去

2)优点

  1. 1.提高应用程序的响应,增强图形化界面用户的体验。
  2. 2.提高cpu利用率
  3. 3.改善程序结构,将复杂的程序分为多个线程。

3)何时需要

  1. 1.程序需要同时执行多个任务。
  2. 2.程序需要实现一些需要等待的任务时,用户输入,文件读写,网络操作,搜索。
  3. 3.需要一些后台运行的程序。

2.创建线程的方式一:继承Thread类

  1. /**
  2. * 多线程的创建:继承Thread类
  3. * 重写run方法-->将线程执行的操作声明在run方法
  4. * 创建子类的对象,通过此对象调用start方法
  5. */
  6. public class MyThread extends Thread {
  7. public void run(){
  8. for (int i = 0; i <100 ; i++) {
  9. System.out.println(this.currentThread().getName()+" "+i);
  10. }
  11. }
  12. }
  13. class Test1{
  14. public static void main(String[] args) {
  15. MyThread m1=new MyThread();
  16. m1.start();
  17. }
  18. }

1)线程的常用方法:

  1. *start():启动当前线程:调用当前线程的run方法
  2. * run();通常需要重写Thread类的run方法,将创建线程要执行的操作声明在此方法
  3. * currentThread():静态方法,返回执行当前代码的线程。
  4. * getName():获取当前线程名
  5. * setName():设置当前线程的名字
  6. * yield():释放当前cpu执行权
  7. * join():在线程a中调用线程b的join方法,a进入阻塞状态,直到b执行完以后,a才结束阻塞状态。优先权
  8. * sleep():挂起一会儿,单位ms
  9. * stop():强制终止,死亡

2)线程优先级:

  1. 1.
  2. MAX_PRIORITY:10
  3. MIN_PRIORITY:1
  4. NORM_PRIORITY:5
  5. 2.如何获取和设置当前线程优先级:
  6. m1.setPriority();
  7. m1.getPriority();
  8. 优先级高并不一定代表一定先执行,只是概率大一点。

3)案例:多窗口卖票

  1. /**
  2. * 继承Thread方法实现多窗口卖票,存在线程安全问题
  3. */
  4. public class ThreadTest1 {
  5. public static void main(String[] args) {
  6. Window w1=new Window();
  7. Window w2=new Window();
  8. w1.start();
  9. w2.start();
  10. }
  11. }
  12. class Window extends Thread{
  13. private static int piao=100;
  14. public void run(){
  15. while (true){
  16. if (piao>0){
  17. System.out.println(currentThread().getName()+" "+piao);
  18. piao--;
  19. }else{
  20. break;
  21. }
  22. }
  23. }
  24. }

3.创建多线程的方式二:实现runnerable接口的方式

  1. /**
  2. * 通过实现runnable接口创建多线程
  3. * 1.创建类a实现runnable接口
  4. * 2.类a重写runnable的run(方法
  5. * 3.在调用方法里创建a的对象;
  6. * 4创建Thread对象b并传入a的对象
  7. * 5.b.start(;
  8. */
  9. public class RunnableTest2 {
  10. public static void main(String[] args) {
  11. myRunnable m1=new myRunnable();
  12. Thread t1=new Thread(m1);
  13. t1.start();
  14. }
  15. }
  16. class myRunnable implements Runnable{
  17. public void run(){
  18. for (int i = 0; i <10 ; i++) {
  19. System.out.println(Thread.currentThread().getName()+" "+i);
  20. }
  21. }
  22. }

1)案例:多窗口卖票

  1. **
  2. * runnable方式实现多窗口卖票,存在线程安全问题
  3. */
  4. public class RunnableTest {
  5. public static void main(String[] args) {
  6. MyRunnable m1=new MyRunnable();
  7. Thread t1=new Thread(m1);
  8. Thread t2=new Thread(m1);
  9. Thread t3=new Thread(m1);
  10. t1.start();
  11. t2.start();
  12. t3.start();
  13. }
  14. }
  15. class MyRunnable implements Runnable{
  16. private int piao;
  17. /**
  18. * 此处不用static修饰的原因,因为上面类中的方法仅仅new了一个此类的对象,
  19. * 所以个Thread对象实际上只是使用了同一个对象的票。
  20. */
  21. public void run(){
  22. while(true){
  23. if (piao>0){
  24. System.out.println(Thread.currentThread().getName()+" :"+piao);
  25. piao--;
  26. }else{
  27. break;
  28. }
  29. }
  30. }
  31. }

2)线程的生命周期

  1. 线程的生命周期
  2. Thread.state();
  3. 1.新建 new
  4. 2.就绪 start
  5. 3.运行 run
  6. 4.阻塞 join,sleep,等待同步锁,wait,(过时的挂起)
  7. 5.死亡 stop

JAVA-SE核心基础篇 - 图6

4.线程的同步

  1. /**
  2. * runnable方式实现多窗口卖票,存在线程安全问题
  3. * 1.买票过程中出现重票错票
  4. * 2.问题描述:当某个线程操作车票的过程中,尚未操作完成,其他线程参与进来,也操作车票。
  5. * 3.如何解决:当一个线程在操作共享数据的时候,其他线程不能参与进来,直到线程a操作完,其他线程才能参与进来,
  6. * 即使线程a出现了阻塞,也不能被改变。
  7. * 4.在Java中我们通过同步机制,来解决线程安全问题。
  8. * 方式一:同步代码块
  9. * synchronized (同步监视器){
  10. * 需要被同步的代码
  11. *不能包多了,也不能包少了
  12. * }
  13. * 说明:1.操作共享数据的代码,就是需要被同步的代码。
  14. * 2.共享数据:多个线程共同操作的数据。
  15. * 3.同步监视器:俗称锁。任何一个类的对象都可以来充当锁。
  16. * 要求:多个线程必须公用同一把锁。
  17. * 补充:在实现runnable接口创建的多线程方式中,我么可以考虑使用this关键字充当锁,
  18. * 在继承Thread类创建的多线程方式中,我们可以考虑使用当前类.class的方式充当锁。
  19. * 方式二:同步方法
  20. *如果操作共享数据的代码,完整的声明在一个方法中,我们不妨将此方法声明为同步的。
  21. * 1.同步方法仍然涉及到同步监视器,只是不需要我i们显示的声明
  22. * 2.非静态的同步方法,同步监视器是this,静态方法的同步监视器是类的本身。
  23. * 5.同步的方式:解决了安全问题--好处
  24. * 操作同步代码时,只能有一个线程参与,其他线程等待,相当于是一个单线程的过程,效率低。--缺点
  25. */

通过继承Thread类实现多窗口卖票

  1. /**
  2. * 使用同步代码块方式解决线程安全问题
  3. * 通过继承Thread类实现多窗口卖票
  4. */
  5. public class TreadTest1 {
  6. public static void main(String[] args) {
  7. window1 w1=new window1();
  8. window1 w2=new window1();
  9. w1.setName("窗口一");
  10. w2.setName("窗口二");
  11. w1.start();
  12. w2.start();
  13. }
  14. }
  15. class window1 extends Thread {
  16. private static int ticket=100;
  17. @Override
  18. public void run() {
  19. while (true){
  20. synchronized (window1.class){
  21. if (ticket>0){
  22. try {
  23. sleep(10);
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. System.out.println(getName()+"卖出了一张票:"+ticket);
  28. ticket--;
  29. }else{
  30. break;
  31. }
  32. }
  33. }
  34. }
  35. }

继承Runnable方式实现多窗口卖票

  1. /**
  2. * 使用同步代码块解决线程安全问题
  3. * 继承Runnable方式实现多窗口卖票
  4. */
  5. public class RunnableTest1 {
  6. public static void main(String[] args) {
  7. window2 w1=new window2();
  8. Thread t1=new Thread(w1);
  9. Thread t2=new Thread(w1);
  10. t1.setName("窗口一:");
  11. t1.setName("窗口二:");
  12. t1.start();
  13. t2.start();
  14. }
  15. }
  16. class window2 implements Runnable{
  17. private int ticket=100;
  18. @Override
  19. public void run() {
  20. while (true){
  21. synchronized (this){
  22. if (ticket>0){
  23. System.out.println(Thread.currentThread().getName()+"卖出了票:"+ticket);
  24. ticket--;
  25. }else{
  26. break;
  27. }
  28. }
  29. }
  30. }
  31. }

通过继承Thread类来创建多线程

  1. /**
  2. * @author 尹会东
  3. * @create 2020 -01 - 21 - 16:41
  4. */
  5. /**
  6. * 通过同步方法解决线程安全问题
  7. * 通过继承Thread类来创建多线程
  8. */
  9. public class ThreadTest2 {
  10. public static void main(String[] args) {
  11. window3 t1=new window3();
  12. window3 t2=new window3();
  13. t1.setName("窗口一:");
  14. t2.setName("窗口二:");
  15. t1.start();
  16. t2.start();
  17. }
  18. }
  19. class window3 extends Thread{
  20. private static int ticket=100;
  21. @Override
  22. public void run() {
  23. while (true){
  24. show();
  25. }
  26. }
  27. public static synchronized void show(){//加static:此时的锁相当于当前类的对象
  28. if (ticket>0){
  29. System.out.println(Thread.currentThread().getName()+"卖出了票:"+ticket);
  30. ticket--;
  31. }
  32. }
  33. }

通过继承runnable方式来创建多线程

  1. /**
  2. * 使用同步方法解决线程安全问题
  3. * 通过继承runnable方式来创建多线程
  4. */
  5. public class RunnableTest2 {
  6. public static void main(String[] args) {
  7. window4 w=new window4();
  8. Thread t1=new Thread(w);
  9. Thread t2=new Thread(w);
  10. t1.setName("窗口一:");
  11. t2.setName("窗口二:");
  12. t1.start();
  13. t2.start();
  14. }
  15. }
  16. class window4 implements Runnable{
  17. private int ticket=100;
  18. @Override
  19. public void run() {
  20. while (true){
  21. show();
  22. }
  23. }
  24. public synchronized void show(){
  25. if (ticket>0){
  26. System.out.println(Thread.currentThread().getName()+"卖出了:"+ticket);
  27. ticket--;
  28. }
  29. }
  30. }

5.线程安全的单例模式之懒汉式

1)通过同步代码块解决懒汉式单例设计模式的线程安全问题

  1. /**
  2. * 通过同步代码块解决懒汉式单例设计模式的线程安全问题
  3. */
  4. public class Thread1 {
  5. private static Thread1 instance=null;
  6. public Thread1 getInstance(){
  7. //效率低
  8. // synchronized (Thread1.class) {
  9. // if(instance==null){
  10. // instance=new Thread1();
  11. // }
  12. // return instance;
  13. // }
  14. /**
  15. * 先判断是否为空,如果为空,进行锁住,否则可以直接获取该对象。
  16. */
  17. if (instance==null){
  18. synchronized (Thread1.class){
  19. if (instance==null){
  20. instance=new Thread1();
  21. }
  22. }
  23. }
  24. return instance;
  25. }
  26. }

2)通过同步方法解决懒汉式单例设计模式的线程安全问题

  1. /**
  2. * 通过同步方法解决懒汉式单例设计模式的线程安全问题
  3. */
  4. public class Thread2 {
  5. private static Thread2 instance = null;
  6. public synchronized Thread2 getInstance() {
  7. if (instance == null) {
  8. instance = new Thread2();
  9. }
  10. return instance;
  11. }
  12. }

6.死锁的问题:

  1. /**
  2. * 死锁问题
  3. * 1.死锁的理解:不同的线程分别占用对方的同步资源不放弃,
  4. * 都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
  5. * 2.说明:
  6. * 1)出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于阻塞状态,无法继续。
  7. * 2)我们使用同步时要避免出现死锁。
  8. */
  1. public class DeadTest {
  2. public static void main(String[] args) {
  3. StringBuffer s1=new StringBuffer();
  4. StringBuffer s2=new StringBuffer();
  5. new Thread(){
  6. public void run(){
  7. synchronized (s1){
  8. s1.append("123");
  9. s2.append("666");
  10. synchronized (s2){
  11. s1.append("456");
  12. s2.append("888");
  13. }
  14. }
  15. }
  16. }.start();
  17. new Thread(){
  18. public void run(){
  19. synchronized (s2){
  20. s1.append("123");
  21. s2.append("666");
  22. synchronized (s1){
  23. s1.append("456");
  24. s2.append("888");
  25. }
  26. }
  27. }
  28. }.start();
  29. }
  30. }

7.Lock锁方式解决线程安全问题:

  1. /**
  2. * 解决线程安全的方式三:Lock锁--jdk5.0新特性
  3. * 面试题:synchronized与lock的异同:
  4. * 同:二者都可以解决线程安全问题
  5. * 异:synchronized机制在执行完相应的同步代码自动解锁(释放同步监视器),lock需要手动启动同步和解锁。
  6. * @author 尹会东
  7. * @create 2020 -01 - 21 - 12:09
  8. */
  1. public class LockTest {
  2. public static void main(String[] args) {
  3. testlock t=new testlock();
  4. Thread t1=new Thread(t);
  5. Thread t2=new Thread(t);
  6. t1.setName("窗口一!");
  7. t2.setName("窗口二:");
  8. t1.start();
  9. t2.start();
  10. }
  11. }
  12. class testlock implements Runnable {
  13. private int ticket = 100;
  14. private ReentrantLock lock = new ReentrantLock();
  15. @Override
  16. public void run() {
  17. while (true) {
  18. try {
  19. lock.lock();
  20. if (ticket > 0) {
  21. System.out.println(Thread.currentThread().getName() + "卖出了票:" + ticket);
  22. ticket--;
  23. } else {
  24. break;
  25. }
  26. } finally {
  27. lock.unlock();
  28. }
  29. }
  30. }
  31. }

练习题:

  1. /**
  2. * 银行一个账户,有两个储户分别向同一个账户存300元,每次存一百,分三次,每次存完打印账户余额。
  3. * 分析:
  4. * 1.是否是多线程问题?是,两个储户线程
  5. * 2.是否共想数据?,账户。
  6. * 3.是否线程安全问题?
  7. * 4.考虑如何解决线程安全问题?同步机制:种方式
  8. */
  9. public class Bank {
  10. public static void main(String[] args) {
  11. Account account=new Account();
  12. Customer c1=new Customer(account);
  13. Customer c2=new Customer(account);
  14. c1.setName("尹会东");
  15. c2.setName("张贝贝");
  16. c1.start();
  17. c2.start();
  18. }
  19. }
  20. class Account {
  21. private double balance=0;
  22. public Account() {
  23. }
  24. public Account(double balance) {
  25. this.balance = balance;
  26. }
  27. public synchronized void save(double money) {
  28. try {
  29. Thread.sleep(1000);
  30. balance+=money;
  31. } catch (InterruptedException e) {
  32. e.printStackTrace();
  33. }
  34. System.out.println(Thread.currentThread().getName()+"存钱成功"+balance);
  35. }
  36. }
  37. class Customer extends Thread{
  38. private Account account;
  39. public Customer(Account account){
  40. this.account=account;
  41. }
  42. public void run(){
  43. for (int i = 0; i <3 ; i++) {
  44. account.save(1000);
  45. }
  46. }
  47. }

8.线程的通信:

  1. /**
  2. * 线程通信的例子:使用两个线程交替打印1-100
  3. * 涉及到的个方法:
  4. * wait():一旦执行此方法,当前线程进入阻塞状态,并释放监视器
  5. * notify():一旦执行此方法,就会唤醒被wait的一个线程,如果有多个线程wait',就会唤醒优先级高的那个。
  6. * notifyAll():会唤醒所被wait的线程。
  7. * 说明:
  8. * 1.使用前提:只能写在同步方法或同步代码块里面
  9. * 2.方法的调用者必须是同步代码块或同步方法中的同步监视器,否则会出现异常。
  10. * 3.这个方法是定义在Object类中的。
  11. * 面试题:sleep和wait的异同:
  12. * 同:都可以让当前线程进入阻塞状态
  13. * 异:1两个方法声明位置不一样:Thread类中声明sleep,Object类中声明wait
  14. * 2调用的范围或者要求是不一样的:sleep随时可以调用,wait只能在同步代码块或同步方法中调用。
  15. * 3关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,wait会释放同步监视器,sleep不会。
  16. *
  17. */
  18. public class Number implements Runnable {
  19. private int num=100;
  20. @Override
  21. public synchronized void run() {
  22. while (true){
  23. notify();//唤醒
  24. if (num>0){
  25. System.out.println(Thread.currentThread().getName()+"打印了:"+num);
  26. num--;
  27. try {
  28. wait();//使得调用wait方法的线程进入阻塞状态,此时会释放锁
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. }else{
  33. break;
  34. }
  35. }
  36. }
  37. }
  38. class test{
  39. public static void main(String[] args) {
  40. Number n=new Number();
  41. Thread t1=new Thread(n);
  42. Thread t2=new Thread(n);
  43. t1.setName("线程一");
  44. t2.setName("线程二");
  45. t1.start();
  46. t2.start();
  47. }
  48. }

经典例题:生产者和消费者问题:

  1. /**
  2. * 生产者消费者问题:线程通信的应用
  3. * 分析:
  4. * 1.多线程问题,生产者,消费者
  5. * 2.存在共享数据,产品/店员
  6. * 3.处理线程安全问题:同步机制
  7. * 4.线程通信:产品超过20停止生产,产品低于0停止购买
  8. */
  9. public class ProductTest {
  10. public static void main(String[] args) {
  11. Shop shop=new Shop();
  12. Producer p=new Producer(shop);
  13. Customers c=new Customers(shop);
  14. Thread t1=new Thread(p);
  15. Thread t2=new Thread(c);
  16. Thread t3=new Thread(c);
  17. t1.setName("生产者");
  18. t2.setName("消费者一");
  19. t3.setName("消费者二");
  20. t1.start();
  21. t2.start();
  22. t3.start();
  23. }
  24. }
  25. class Producer implements Runnable{
  26. private Shop shop;
  27. public Producer(Shop shop){
  28. this.shop=shop;
  29. }
  30. @Override
  31. public void run() {
  32. System.out.println("生产者开始生产东西");
  33. while (true){
  34. try {
  35. sleep(50);
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. shop.in();
  40. }
  41. }
  42. }
  43. class Customers implements Runnable{
  44. private Shop shop;
  45. public Customers(Shop shop){
  46. this.shop=shop;
  47. }
  48. @Override
  49. public void run() {
  50. System.out.println("消费者开始购买东西");
  51. while (true){
  52. try {
  53. sleep(100);
  54. } catch (InterruptedException e) {
  55. e.printStackTrace();
  56. }
  57. shop.out();
  58. }
  59. }
  60. }
  61. class Shop{
  62. private int thing=0;
  63. public synchronized void in() {
  64. if (thing<20){
  65. thing++;
  66. System.out.println(Thread.currentThread().getName()+"生产了东西"+thing);
  67. notify();
  68. }else{
  69. try {
  70. wait();
  71. } catch (InterruptedException e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. }
  76. public synchronized void out(){
  77. if (thing>0) {
  78. System.out.println(Thread.currentThread().getName()+"购买了东西"+thing);
  79. thing--;
  80. notify();
  81. }else{
  82. try {
  83. wait();
  84. } catch (InterruptedException e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. }
  89. }

9.创建多线程的方式三:实现Callable接口

  1. /**
  2. * 创建线程的方式:实现Callable接口的方式
  3. * 1.创建一个实现Callable接口的实现类(重写call方法)的对象
  4. * 2.创建一个FutureTask对象并传入Callable接口的实现类的对象
  5. * 3.创建一个Thread类对象并传入FutureTask对象
  6. * 4.get()方法的返回值就是FutureTask构造器参数callable实现类重写的call(的返回值。
  7. * 面试题:如何理解实现Callable接口创建多线程比实现runnable接口创建多线程强大?
  8. * 1call(方法可以返回值
  9. * 2call(方法可以抛出异常被外面的操作捕获并获取异常信息‘
  10. * 3callable接口支持泛型
  11. * @author 尹会东
  12. * @create 2020 -01 - 21 - 14:00
  13. */
  14. public class Demo1 {
  15. public static void main(String[] args) {
  16. Share share = new Share();
  17. new Thread(new FutureTask(()->{
  18. for (int i = 0; i < 100; i++) share.print(); return null;}),"AA").start();
  19. new Thread(new FutureTask(()->{
  20. for (int i = 0; i < 100; i++) share.print(); return null;}),"BB").start();
  21. }
  22. }
  23. class Share {
  24. private Integer num=0;
  25. private ReentrantLock lock=new ReentrantLock();
  26. private Condition cd=lock.newCondition();
  27. public void print(){
  28. try {
  29. lock.lock();
  30. while (num<100){
  31. cd.signal();
  32. System.out.println(Thread.currentThread().getName()+"打印了一张票:"+ ++num+"还剩"+
  33. (100-num) +"张票。");
  34. cd.await();
  35. }
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. } finally {
  39. lock.unlock();
  40. }
  41. }
  42. }

10.创建多线程的方式四:使用线程池

  1. /**
  2. * 创建线程的方式四:使用线程池
  3. * 使用线程池的好处:
  4. * 1.提高响应速度
  5. * 2.降低资源消耗
  6. * 3.便于线程管理
  7. * 属性:
  8. * corePoolSize:核心池的大小
  9. * maximumPoolSize:最大线程数
  10. * keepAliveTime:线程没任务时最多保持多长时间后终止
  11. *
  12. * @author 尹会东
  13. * @create 2020 -01 - 21 - 14:43
  14. */
  15. class num implements Runnable {
  16. private int num = 100;
  17. @Override
  18. public void run() {
  19. while (true) {
  20. synchronized (com.qtguigu.fuxi.num.class) {
  21. if (num > 0) {
  22. System.out.println(Thread.currentThread().getName() + num);
  23. num--;
  24. } else {
  25. break;
  26. }
  27. }
  28. }
  29. }
  30. }
  31. public class PoolTest {
  32. public static void main(String[] args) {
  33. ExecutorService service = Executors.newFixedThreadPool(10);
  34. num n1 = new num();
  35. //如果需要设置属性需要把service类型转换为ThreadPoolExecutor
  36. //ThreadPoolExecutor e = (ThreadPoolExecutor) service;
  37. service.execute(n1);//2.1执行:适合适用于runnable(传入一个实现runnable接口的对象
  38. // service.submit();//2.1提交:适合适用于callable(传入一个实现callable接口的对象
  39. service.shutdown();//3.关闭线程
  40. }
  41. }

七,常用类

1.String

1)String内存解析

JAVA-SE核心基础篇 - 图7

2)String分析

  1. /**
  2. * 1.声明为final,不可被继承。
  3. * 2.实现了java.io.Serializable接口,表示字符串是支持序列化的。
  4. * 3.实现了Comparable<String>接口,表示String可以比较大小。
  5. * 4.String内部定义了final char[] value用于存储字符串数据
  6. * 5.String代表了不可变的字符序列,简称:不可变性。
  7. * 1)当对字符串重新赋值,需要重新指定内存区域,不能再原有的地址重新赋值。
  8. * 2)当对现的字符串进行连接操作时,需要重新指定内存区域,不能再原有的地址重新赋值。
  9. * 3)当调用String的replace(方法修改字符或字符串时,也必须重新指定内存区域进行赋值。
  10. * 6.通过字面量的方式给字符串赋值,此时的字符串值声明在字符串常量池中
  11. * 7.字符串常量池不会存储相同内容的字符串的。
  12. */
  1. String s1="abc";//字面量的定义方式
  2. String s2="abc";
  3. //s1="hello";
  4. System.out.println(s1==s2);//比较s1和s2的地址值
  5. System.out.println("**********************************");
  6. String s3="abc";
  7. s3+="def";
  8. System.out.println(s1==s3);//false
  9. System.out.println("**********************************");
  10. String s4="abc";
  11. String s5=s4.replace('a','m');
  12. System.out.println(s4+" "+s5);//abc mbc

3)String实例化

  1. /**
  2. * String的实例化方式:
  3. * 1.通过字面量定义的方式:
  4. *数据声明在方法区对应的字符串常量池中
  5. * 2.通过new+构造器的方式:
  6. * 保存的地址值在堆空间中
  7. * 面试题:String s3=new String("java");在内存中创建了几个对象?
  8. * 两个:一个是堆空间中new的结构,一个是char【】数组对应的常量池的数据:java
  9. */
  1. //此时的s1和s2数据声明在方法区对应的字符串常量池中
  2. String s1="java";
  3. String s2="java";
  4. //此时s3和s4保存的地址值在堆空间中
  5. String s3=new String("java");
  6. String s4=new String("java");
  7. System.out.println(s1==s2);//true
  8. System.out.println(s1==s3);//false
  9. System.out.println(s3==s4);//false

4)图解两种创建字符串方式的区别

JAVA-SE核心基础篇 - 图8

5)图解字符串的存储

JAVA-SE核心基础篇 - 图9

6)图解字符串对象的存储

JAVA-SE核心基础篇 - 图10

7)String不同拼接操作的对比:

  1. /*
  2. * 1.常量与常量的拼接结果在常量池,且常量池中不会存在相同内容的常量。
  3. * 2.只要其中一个是变量,结果就在堆中。
  4. * 3.String s8=s5.intern();此时的返回值得到的s8是使用的常量池中已经存在的javahadoop
  5. * 4.intern的返回值在方法去的常量池
  6. */
  7. String s1="java";//常量池
  8. String s2="hadoop";//常量池
  9. String s3="javahadoop";//常量池
  10. String s4="java"+"hadoop";//常量池
  11. String s5=s1+"hadoop";//堆空间
  12. String s6="java"+s2;//堆空间
  13. String s7=s1+s2;//堆空间
  14. String s8=s5.intern();//常量池
  15. System.out.println(s3==s4);//true
  16. System.out.println(s4==s5);//false
  17. System.out.println(s3==s5);//false
  18. System.out.println(s5==s6);//false
  19. System.out.println(s3==s7);//false
  20. System.out.println(s5==s7);//false
  21. System.out.println(s6==s7);//false
  22. System.out.println(s8==s3);//true

面试题

  1. /**
  2. * String的一道面试题:
  3. * str传递给change方法的形参,只是形参的地址也指向了str所指向的地址,形参改变的话,因为是String
  4. * 类型,不可变性,所以形参只是重新开辟一一个value=”test ok"的地址。
  5. * 而基本数据类型,改变他的值,就是把原地址的值给改变了。
  6. */
  7. public class StringTest4 {
  8. String str=new String("good");
  9. char []ch={'t','e','s','t'};
  10. public static void main(String[] args) {
  11. StringTest4 ex=new StringTest4();
  12. ex.change(ex.str,ex.ch);
  13. System.out.println(ex.str+" "+ex.ch);//good best
  14. }
  15. private void change(String str, char[] ch) {
  16. str="test ok";
  17. ch[0]='b';
  18. }
  19. }

8)String的常用方法:

  1. public static void main(String[] args) {
  2. String s1="hello";
  3. String s2="world";
  4. System.out.println(s1.length());//返回数组的长度 5
  5. System.out.println(s1.charAt(3));//返回指定索引的字符 l
  6. System.out.println(s1.isEmpty());//判空 false
  7. System.out.println(s1.toLowerCase());//将String中所字符转换为小写 hello
  8. System.out.println(s1.toUpperCase());//将String中所字符转换为大写 HELLO
  9. System.out.println(s1.trim());//返回字符串副本,忽略前后的空白 hello
  10. System.out.println(s1.equals(s2));//比较字符串内容是否相同 false
  11. System.out.println(s1.equalsIgnoreCase(s2));//忽略大小写的比较字符串是否相同 false
  12. System.out.println(s1.compareTo(s2));//比较两个字符串的大小 -15
  13. System.out.println(s1.substring(2));//从指定位置开始截取 llo
  14. System.out.println(s1.substring(2,4));//截取指定位置的字符串 ll
  15. }
  1. public static void main(String[] args) {
  2. String s1="helloworld";
  3. String s2="HelloWorld";
  4. System.out.println(s1.endsWith("ld"));//是否已指定字符串结尾 true
  5. System.out.println(s1.startsWith("he"));//是否以指定的字符串开始 true
  6. System.out.println(s1.startsWith("wo",5));//是否在指定位置以这个字符串开始 //true
  7. System.out.println(s1.contains("owo"));//判断是否包含这个字符串 true
  8. System.out.println(s1.indexOf("lo"));//指定字符串所在的位置 3,没的话返回-1
  9. System.out.println(s1.indexOf("lo",5));//从指定位置找指定的字符串 -1
  10. System.out.println(s1.lastIndexOf("lo"));//从后往前找 3
  11. System.out.println(s1.replace('l','y'));//替换字符
  12. System.out.println(s1.replace("hello","666"));//替换字符串

9)String和其他类型之间的转换

  1. /**
  2. * String和其他类型之间的转换
  3. */
  4. public class StringTest7 {
  5. public static void main(String[] args) {
  6. //String与基本数据类型,包装类的转换
  7. String str1="123";
  8. int num=Integer.parseInt(str1);//String-->int/integer
  9. String str2=String.valueOf(num);//int/integer-->String
  10. //String与char[]之间的转换
  11. String str3="123456";
  12. char[] array = str3.toCharArray();//String-->char[]数组
  13. String str4 = new String(array);//char[]-->String
  14. //String和字节数组之间的转换byte[]
  15. String str5="123456";
  16. byte [] bytes= str5.getBytes(); //String-->byte[] 编码
  17. String str6 = new String(bytes);//byte[]-->String 解码
  18. /**
  19. * 编码:字符串转换成字节。
  20. * 解码:字节转换为字符串。
  21. */
  22. }
  23. }

10)String的四道面试题:

  1. /**
  2. * 模拟一个trim方法,去除字符串两端的空格
  3. */
  4. public static void main(String[] args) {
  5. String str1 = " 123456 ";
  6. char[] array = str1.toCharArray();
  7. char[] array2 = new char[str1.length()];
  8. int num = 0;
  9. for (int i = 0; i < array.length; i++) {
  10. if (array[i] == ' ') {
  11. continue;
  12. } else {
  13. array2[num] = array[i];
  14. num++;
  15. }
  16. }
  17. String string = new String(array2);
  18. System.out.println(string.substring(0, num));
  19. }
  1. /**
  2. * 交换指定位置字符串
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. int start=2;
  7. int end=5;
  8. String str1="0123456789";
  9. char[] array = str1.toCharArray();
  10. for (int i = start; i <(start+end)/2+1 ; i++) {
  11. char a=array[i];
  12. array[i]=array[end+start-i];
  13. array[end+start-i]=a;
  14. }
  15. String s = new String(array);
  16. System.out.println(s);
  17. }
  1. /**
  2. * 获取一个字符串在另一个字符串中出现的次数
  3. */
  4. public static void main(String[] args) {
  5. String str1="我爱中国,中国共产党万岁!";
  6. String str2="中国";
  7. int sum=0;
  8. while (str1.contains(str2)){
  9. sum++;
  10. int num=str1.indexOf(str2);
  11. str1=str1.substring(num+str2.length());
  12. }
  13. System.out.println(sum);
  14. }
  1. /**
  2. * 对字符串中的字符进行自然排序
  3. */
  4. public static void main(String[] args) {
  5. String str1="9876543210";
  6. char[] array = str1.toCharArray();
  7. Arrays.sort(array);
  8. String str2 = new String(array);
  9. System.out.println(str2);
  10. }

11)StringBuffer和StringBuilder

  1. /**
  2. * 关于StringBuffer和StringBuilder的使用
  3. * 1.StringBuffer的常用方法:
  4. * StringBuffer sb1 = new StringBuffer("abcdef");
  5. * sb1.append("A");//abcdefA
  6. * sb1.delete(1, 4);//aefA
  7. * sb1.replace(2,3,"hello");//aehelloA
  8. * sb1.insert(2,"HELLO");//aeHELLOhelloA
  9. * sb1.reverse();//反转 AollehOLLEHea
  10. * sb1.charAt(1);
  11. * sb1.indexOf("A");
  12. * System.out.println(sb1);
  13. * 2.StringBuilder的常用方法:
  14. * 同StringBuffer
  15. * String,StringBuffer,StringBuilder者的异同:
  16. * 相同点:底层结构使用char[]数组存取,String的char[]数组用了final修饰
  17. * String:不可变字符串,
  18. * StringBuffer:可变的字符序列,线程安全的,效率低。
  19. * StringBuilder:可变的字符序列,线程不安全的,效率高。jdk1.5
  20. * String,StringBuffer,StringBuilder者效率对比:
  21. * StringBuilder效率最高,StringBuffer第二,String第3
  22. * 源码分析:
  23. * String str=new String();//char[] value=new char[0];
  24. * String str1=new String("abc");//char [] value=new char[] {'a','b','c'};
  25. * <p>
  26. * StringBuffer sb1=new StringBuffer();//char value[]=new char[16];底层创建了一个长度为16的char数组。
  27. * sb1.append('a');//value[0]='a';
  28. * sb1.append('b');//value[1]='b';
  29. * StringBuffer sb2=new StringBuffer("abc");//char []value=new char ["abc".length()+16];
  30. * 问题一:System.out.println(sb2.length());//3
  31. * 因为底层返回的长度只是字符串的长度不是数组的长度
  32. * 问题二:扩容问题:如果要添加的数据底层数组装不下了,那就需要扩容底层的数组。
  33. * 默认情况下,扩容为原来容量的2倍+2,同时将原数组中的元素复制到新的数组中。
  34. * 指导意义:开发中建议大家使用:StringBuffer或StringBuilder
  35. */
  36. public class StringBufferTest {
  37. public static void main(String[] args) {
  38. StringBuffer sb1 = new StringBuffer("abcdef");
  39. sb1.append("A");//abcdefA
  40. sb1.delete(1, 4);//aefA
  41. sb1.replace(2,3,"hello");//aehelloA
  42. sb1.insert(2,"HELLO");//aeHELLOhelloA
  43. sb1.reverse();//反转 AollehOLLEHea
  44. sb1.charAt(1);
  45. sb1.indexOf("A");
  46. System.out.println(sb1);
  47. }
  48. }

面试题

  1. public static void main(String[] args) {
  2. String s1=null;
  3. StringBuffer sb1=new StringBuffer();
  4. sb1.append(s1);
  5. /**
  6. * StringBuffer的append方法会将添加进来的null字符串转化为”null“字符串添加进去。
  7. * 所以此处不会出空指针异常
  8. */
  9. System.out.println(sb1.length());//4
  10. System.out.println(sb1);//"null"
  11. StringBuffer sb2=new StringBuffer(s1);
  12. /**
  13. * StringBuffer的构造器并不会对传入的null进行处理
  14. * 所以此处空指针异常
  15. */
  16. System.out.println(sb2);//java.lang.NullPointerException
  17. }

String,StringBuffer,StringBuilder的区别

  1. /**
  2. * :
  3. * 1.String:不可变字符串。任何对内容的修改,String指向的地址都发生了变化。
  4. * 1String a="123"; a在栈里面,指向字符串常量池中的123所对应的地址。当修改a的内容,就相当于
  5. * 将a所指向的地址做出了改变。
  6. * 2String a=new String("123");a在栈里面,指向堆空间中new出来的结构,new出来的结构指向字符串常量池
  7. * 中123对应的地址,改变a的内容,还是相当于改变了a所指向的地址。
  8. * 2.StringBuffer:线程安全的,jdk1.1,效率低。
  9. * 3.StringBuilder:线程不安全,效率高。jdk1.5新特性。底层先创建一个长度为16的数组,
  10. * 每次添加值,就是给数组对应的位置赋值,扩容问题:每次扩容为原来的2倍+2.再将原来的数组复制进去。
  11. *
  12. */

2.时间日期类

1)jdk8之前的时间日期API

①时间戳

  1. @Test
  2. public void test(){
  3. long millis = System.currentTimeMillis();
  4. System.out.println(millis);
  5. }

②java.util.Date

  1. -->java.sql.Date
    1. 两个构造器的使用
    1. 两个方法的使用
    1. toString()显示当前的年月日时分秒
    1. date.getTime()时间戳
  1. @Test
  2. public void test2(){
  3. Date date=new Date();
  4. System.out.println(date.toString());//Thu Jan 30 17:00:01 CST 2020
  5. System.out.println(date.getTime());//1580374801066
  6. }
  7. @Test
  8. public void test3(){
  9. Date date = new Date(System.currentTimeMillis());
  10. System.out.println(date.toString());//Thu Jan 30 17:00:33 CST 2020
  11. }

③java.sql.Date

对应着数据库中的日期类型变量
如何实例化
sql.Date—>util.Date直接赋值
util.Date—>sql.Date

  1. @Test
  2. public void test4(){
  3. java.sql.Date date=new java.sql.Date(System.currentTimeMillis());
  4. System.out.println(date.toString());
  5. Date date1=new Date();
  6. long time = date1.getTime();
  7. java.sql.Date date2=new java.sql.Date(time);
  8. System.out.println(date2.toString());
  9. }

④SimpleDateFormat类

  • 实例化
  • 格式化:日期—>文本(字符串)
  • 解析:文本(字符串)—>日期
  1. @Test
  2. public void test6() throws ParseException {
  3. //实例化
  4. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  5. Date date=new Date();
  6. //格式化
  7. String s = format.format(date);
  8. System.out.println(s);//2020-01-30 05:24:23
  9. //解析
  10. Date date1 = format.parse(s);
  11. System.out.println(date1);//Thu Jan 30 05:24:23 CST 2020
  12. }

⑤Calendar日历类的使用(抽象类)

  • 1.实例化:
  • ①创建子类的对象(不建议)
  • ②调用其静态方法
  1. @Test
  2. public void test7() {
  3. Calendar calendar = Calendar.getInstance();
  4. //2.常用方法:
  5. // calendar.get();
  6. int days = calendar.get(Calendar.DAY_OF_MONTH);
  7. System.out.println(days);//这个月的第几天
  8. // calendar.set();//修改calendar本身
  9. calendar.set(Calendar.DAY_OF_MONTH, 20);
  10. System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
  11. // calendar.add();//修改calendar本身
  12. calendar.add(Calendar.DAY_OF_MONTH, 20);
  13. System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
  14. // calendar.getTime();
  15. Date time = calendar.getTime();
  16. System.out.println(time);
  17. // calendar.setTime();
  18. Date date = new Date();
  19. calendar.setTime(date);
  20. System.out.println(calendar.getTime());
  21. }

⑥练习

字符串2020-09-08转换为java.sql.Date
  1. @Test
  2. public void test8() throws ParseException {
  3. String str="2020-09-08";
  4. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  5. Date date = format.parse(str);
  6. long time = date.getTime();
  7. java.sql.Date sqlDate=new java.sql.Date(time);
  8. System.out.println(sqlDate.toString());
  9. }

渔夫三天打鱼,两天晒网。1990-01-01
  1. * 问:渔夫在打鱼还是在晒网?
  2. * 2020-09-08
  3. * 总天数%5==1,2,3打鱼;0,4晒网
  4. * 总天数?
  1. @Test
  2. public void test9() throws ParseException {
  3. String start="1990-01-01";
  4. String end="2020-09-08";
  5. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  6. Date date = format.parse(start);
  7. Date date1 = format.parse(end);
  8. long time = date.getTime();
  9. long time1 = date1.getTime();
  10. long day=(time1-time)/(1000*60*60*24)+1;
  11. if (day%5==0||day%5==4){
  12. System.out.println("今天筛网");
  13. }else{
  14. System.out.println("今天打🐟");
  15. }
  16. }

2)jdk8时间日期API

①LocalDate,LocalTime,LocalDateTime的使用

  1. @Test
  2. public void test() {
  3. //实例化方式一:获取当前时间
  4. LocalDate now = LocalDate.now();
  5. LocalTime now1 = LocalTime.now();
  6. LocalDateTime now2 = LocalDateTime.now();
  7. System.out.println(now);//2020-01-30
  8. System.out.println(now1);//13:57:33.240
  9. System.out.println(now2);//2020-01-30T13:57:33.240
  10. }
  11. @Test
  12. public void test2() {
  13. //实例化方式二:获取指定的日期时间
  14. LocalDate date = LocalDate.of(2020, 2, 2);
  15. System.out.println(date);//2020-02-02
  16. }
  17. @Test
  18. public void test3() {
  19. LocalDateTime time = LocalDateTime.of(2012, 2, 2, 12, 53, 23);
  20. System.out.println(time.getDayOfMonth());//2
  21. System.out.println(time.getDayOfWeek());//THURSDAY
  22. System.out.println(time.getDayOfYear());//33
  23. System.out.println(time.getHour());//12
  24. System.out.println(time.getMonthValue());//2
  25. }
  26. @Test
  27. public void test4() {
  28. LocalDateTime time = LocalDateTime.of(2012, 2, 2, 12, 53, 23);
  29. LocalDateTime localDateTime = time.withDayOfMonth(2);//不可变性,重置
  30. System.out.println(localDateTime);
  31. LocalDateTime plusDays = time.plusDays(108);//不可变性,加
  32. System.out.println(plusDays);
  33. LocalDateTime minusDays = time.minusDays(20);//不可变性,减
  34. System.out.println(minusDays);
  35. }

②Instant类

  1. @Test
  2. public void test(){
  3. //实例化
  4. Instant now = Instant.now();
  5. System.out.println(now);//本初子午线的时间
  6. OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
  7. System.out.println(offsetDateTime);//当前时间
  8. long second = offsetDateTime.toEpochSecond();
  9. System.out.println(second);//获取m数s
  10. Instant instant = Instant.ofEpochMilli(1580365450L*1000);
  11. System.out.println(instant);
  12. }

③格式化或者解析时间日期

  1. @Test
  2. public void test(){
  3. //自定义格式
  4. DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
  5. //格式化
  6. String str=formatter.format(LocalDateTime.now());//2020-01-30 04:37:39
  7. System.out.println(str);//
  8. //解析
  9. TemporalAccessor accessor=formatter.parse("2020-02-18 03:52:09");
  10. System.out.println(accessor);
  11. }

3.比较器与其他类

1)比较器

  1. Java中的对象,只能使用==或者!=进行比较,不能使用<或>进行比较,但是在实际开发中,我们需要对多个对象进行排序,言外之意,就需要比较对象的大小。如何实现?使用两个接口,Comparable或Comparator。
  2. liang者使用对比:
  3. 1)Comparable:让类去继承接口,对象具有比较大小的属性
  4. 2)Comparator:临时new一个匿名对象重写方法,传入对象进行比较,对象不具有比较大小的属性
  5. * Comparable接口的使用:自然排序
  6. * 1.String或者包装类实现了Comparable接口重写了ComepareTo方法,给出了比较两个对象大小的方法。
  7. * 2.重写CompareTo()方法的规则:
  8. * 如果当前对象this大于形参对象obj,则返回正整数,
  9. * 如果当前对象this小于形参对象obj,则返回负整数,
  10. * 否则返回0;
  11. * 3.对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写CompareTo方法。
  12. * 在方法中指明如何排序。
  1. public static void main(String[] args) {
  2. Goods[]arr=new Goods[4];
  3. arr[0]=new Goods("lenovo",50.0);
  4. arr[1]=new Goods("honor",50.0);
  5. arr[2]=new Goods("iphone",888.8);
  6. arr[3]=new Goods("zte",66.6);
  7. Arrays.sort(arr);
  8. System.out.println(Arrays.toString(arr));
  9. }
  10. }
  11. class Goods implements Comparable{
  12. private String name;
  13. private double price;
  14. public Goods() {
  15. }
  16. public Goods(String name, double price) {
  17. this.name = name;
  18. this.price = price;
  19. }
  20. public String getName() {
  21. return name;
  22. }
  23. public void setName(String name) {
  24. this.name = name;
  25. }
  26. public double getPrice() {
  27. return price;
  28. }
  29. @Override
  30. public String toString() {
  31. return "Goods{" +
  32. "name='" + name + '\'' +
  33. ", price=" + price +
  34. '}';
  35. }
  36. public void setPrice(double price) {
  37. this.price = price;
  38. }
  39. @Override
  40. public int compareTo(Object o) {
  41. if (o instanceof Goods){
  42. Goods goods= (Goods) o;
  43. return this.price>goods.price?1:(this.price<goods.price?-1:(this.name.compareTo(goods.name)));
  44. // return this.name.compareTo(goods.name);
  45. }
  46. throw new RuntimeException("传入的数据类型不一致!");
  47. }
  48. }
  1. * Comparator接口:定制排序
  2. * 1.当元素的北京没有实现java.long.Comparable接口而又不方便修改代码
  3. * 2.实现了java.lang.Comparable接口的排序规则不适合当前的操作
  4. * 3.抽象方法:compare(Object obj1,Object obj2)
  1. public static void main(String[] args) {
  2. Dog[]arr=new Dog[4];
  3. arr[0]=new Dog("lenovo",50);
  4. arr[1]=new Dog("honor",50);
  5. arr[2]=new Dog("iphone",40);
  6. arr[3]=new Dog("zte",60);
  7. Arrays.sort(arr, new Comparator<Dog>() {
  8. @Override
  9. public int compare(Dog o1, Dog o2) {
  10. //先照名字从低到高,再照年龄从高到低
  11. if (o1.getName().equals(o2.getName())){
  12. return -Double.compare(o1.getAge(),o2.getAge());
  13. }else{
  14. return o1.getName().compareTo(o2.getName());
  15. }
  16. }
  17. });
  18. System.out.println(Arrays.toString(arr));
  19. }
  20. }
  21. class Dog {
  22. private String name;
  23. private int age;
  24. public Dog() {
  25. }
  26. public Dog(String name, int age) {
  27. this.name = name;
  28. this.age = age;
  29. }
  30. public String getName() {
  31. return name;
  32. }
  33. public void setName(String name) {
  34. this.name = name;
  35. }
  36. public int getAge() {
  37. return age;
  38. }
  39. public void setAge(int age) {
  40. this.age = age;
  41. }
  42. @Override
  43. public String toString() {
  44. return "Dog{" +
  45. "name='" + name + '\'' +
  46. ", age=" + age +
  47. '}';
  48. }
  49. }

2)Math类

  1. /**
  2. * Math.abs();//绝对值
  3. * Math.sqrt();//平方根
  4. * Math.pow();//a的b次幂
  5. * Math.log();//自然对数
  6. * Math.exp();//e为底指数
  7. * Math.max();//
  8. * Math.min();//
  9. * Math.random();//随机数
  10. * Math.round();//double/float转long
  11. */

3)BigInteger和BigDecimal

高精度整数运算器和高精度浮点数运算器

八,枚举类和注解

1.枚举类

1)枚举类的使用

  • 1.枚举的理解:类的对象只有有限个,确定的。我们称此类为枚举类。
  • 2.当我们定义一组常量时,建议使用枚举类。
  • 3.如果枚举类的对象只有一个,可以看作时单例设计模式。

2)如何定义枚举类

方式一:jdk5.0之前自定义枚举类

  1. /**
  2. * @author yinhuidong
  3. * @createTime 2020-04-08-13:11
  4. * jdk5.0之前自定义枚举类
  5. */
  6. public class Season {
  7. private final String name;
  8. private final String desc;
  9. private Season(String name,String desc){
  10. this.name=name;
  11. this.desc=desc;
  12. }
  13. public static final Season SPRING=new Season("春天","春暖花开");
  14. public static final Season SUMMER=new Season("夏天","夏日炎炎");
  15. public static final Season AUTUMO=new Season("秋天","秋高气爽");
  16. public static final Season WINTER=new Season("冬天","雪花飘飘");
  17. public String getName() {
  18. return name;
  19. }
  20. public String getDesc() {
  21. return desc;
  22. }
  23. @Override
  24. public String toString() {
  25. return name;
  26. }
  27. }
  28. /**
  29. *测试jdk5.0之前的枚举类
  30. */
  31. class Test1{
  32. public static void main(String[] args) {
  33. //System.out.println(Season.SPRING);
  34. Season season=Season.SPRING;
  35. }
  36. }

jdk5.0使用enum关键字定义枚举类

  1. /**
  2. * @author yinhuidong
  3. * @createTime 2020-04-08-17:50
  4. */
  5. interface Info{
  6. void show();
  7. }
  8. public enum Status implements Info{
  9. FREE{
  10. public void show(){
  11. System.out.println("空闲");
  12. }
  13. },
  14. BUSY{
  15. public void show(){
  16. System.out.println("忙碌");
  17. }
  18. },
  19. WORK{
  20. public void show(){
  21. System.out.println("工作");
  22. }
  23. };
  24. private Status(){
  25. }
  26. }
  27. /**
  28. *jdk5.0之后使用enum关键字定义枚举类
  29. */
  30. class Test2{
  31. public static void main(String[] args) {
  32. Status status= FREE;
  33. status.show();
  34. Status[] values = Status.values();
  35. for (int i=0;i<values.length;i++){
  36. System.out.println(values[i]);
  37. }
  38. System.out.println(FREE.toString());
  39. System.out.println(Status.valueOf("FREE"));
  40. }
  41. }

3)Enum类中常用方法

  • value()

  • valueof()

  • toString()

    1. State[] states = State.values();
    2. for (int i = 0; i <states.length ; i++) {
    3. System.out.print(states[i]+" ");//FREE HARD SLEEP
    4. }
    5. System.out.println(free.toString());//FREE
    6. System.out.println(State.valueOf("FREE"));//FREE,如果没此对象就会报异常。java.lang.IllegalArgumentException

4)使用enum关键字定义的枚举类实现接口的情况

*情况一:实现接口,在enum的枚举类中重写方法

  • 情况二:实现接口,在enum的枚举类中声明的每个对象下都重写方法
    1. FREE{
    2. @Override
    3. public void show() {
    4. System.out.println("空闲!");
    5. }
    6. },

2.注解

1.Annotation使用示例

  1. /**
  2. * @author yinhuidong
  3. * @createTime 2020-04-08-20:56
  4. * 1.Annotation使用示例
  5. * 1)文档注释中的注解
  6. * @return
  7. * @Exception
  8. * @param
  9. * @see
  10. * 2)jdk三个内置的注解
  11. * 1.@Override 子类重写父类方法,编译期间校验
  12. * 2.@Deprecated 过时的或危险的(可能造成线程死锁)
  13. * 3.@SuppressWarnings() 未使用提醒
  14. * 3)组件框架,跟踪代码依赖性,代替配置文件
  15. * @Autowrited
  16. */

2.自定义注解与元注解

  1. /**
  2. * @author yinhuidong
  3. * @createTime 2020-04-08-21:02
  4. * 自定义注解:参照@SuppressWarnings()
  5. * 如果自定义的注解没有成员,那就代表一个标识
  6. * 如果自定义注解有成员,需要在使用时指定成员的值
  7. * 自定义注解必须配合反射
  8. * 如果想食用反射操作注解,那么注解必须声明为RUNTIME
  9. *
  10. * 元注解:可以修饰其他注解的注解
  11. * 1. Retention:指明修饰的注解的生命周期:SOURCE\CLASS(默认行为)\RUNTIME
  12. * *只有声明为runtime的注解,才能通过反射获取
  13. * 2.Target:用于指定被修饰的结构有哪些
  14. * 3.Documented:被他修饰的注解可以被文档注释读取,保留下来
  15. * 4.Inherited:具有继承性,父类被此注解修饰,子类自动继承父类的注解
  16. */
  17. public @interface MyAnnotation {
  18. String value() default "hello";
  19. //String类型的属性,默认值为hello
  20. }

1.Retention

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target(ElementType.ANNOTATION_TYPE)
  4. public @interface Retention {
  5. /**
  6. * Returns the retention policy.
  7. * @return the retention policy
  8. */
  9. RetentionPolicy value();
  10. }
  11. 继续查看RetentionPolicy,这是一个枚举类
  12. public enum RetentionPolicy {
  13. /**
  14. * Annotations are to be discarded by the compiler.
  15. */
  16. SOURCE,
  17. /**
  18. * Annotations are to be recorded in the class file by the compiler
  19. * but need not be retained by the VM at run time. This is the default
  20. * behavior.
  21. */
  22. CLASS,
  23. /**
  24. * Annotations are to be recorded in the class file by the compiler and
  25. * retained by the VM at run time, so they may be read reflectively.
  26. *
  27. * @see java.lang.reflect.AnnotatedElement
  28. */
  29. RUNTIME
  30. }
  31. SOURCE:编译时起作用
  32. CLASS:字节码文件
  33. RUNTIME:运行时

2.Target

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target(ElementType.ANNOTATION_TYPE)
  4. public @interface Target {
  5. /**
  6. * Returns an array of the kinds of elements an annotation type
  7. * can be applied to.
  8. * @return an array of the kinds of elements an annotation type
  9. * can be applied to
  10. */
  11. ElementType[] value();
  12. }
  13. 继续点击进入ElementType
  14. 又是一个枚举类:指定可以修饰的类型
  15. public enum ElementType {
  16. /** Class, interface (including annotation type), or enum declaration */
  17. TYPE,//类上
  18. /** Field declaration (includes enum constants) */
  19. FIELD,//属性
  20. /** Method declaration */
  21. METHOD,//方法
  22. /** Formal parameter declaration */
  23. PARAMETER,//成员变量
  24. /** Constructor declaration */
  25. CONSTRUCTOR,//构造器
  26. /** Local variable declaration */
  27. LOCAL_VARIABLE,//局部变量
  28. /** Annotation type declaration */
  29. ANNOTATION_TYPE,//注解类型
  30. /** Package declaration */
  31. PACKAGE,//包
  32. /**
  33. * Type parameter declaration
  34. *
  35. * @since 1.8
  36. */
  37. TYPE_PARAMETER,//泛型
  38. /**
  39. * Use of a type
  40. *
  41. * @since 1.8
  42. */
  43. TYPE_USE //可重复注解
  44. }

3.Documented

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target(ElementType.ANNOTATION_TYPE)
  4. public @interface Documented {
  5. }
  6. 指示默认情况下iavadoc和类似工具将记录具有类型的注释。此类型应用于对类型声明进行注释,这些类型的注释会影响其客户端对带注释的元素的使用。如果类型声明是用文档注释的,那么它的注释将成为公共API的一部分注释元素的。

4.Inherited

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target(ElementType.ANNOTATION_TYPE)
  4. public @interface Inherited {
  5. }
  6. 表示注释类型是自动继承的。如果继承的元注释存在于注释类型上声明,用户查询类声明上的注释类型,而类声明没有针对这种类型的注释,然后类的超类将自动查询注释类型。此过程将重复进行,直到找到此类型的注释,或找到类层次结构的顶部(对象)是达到了。如果没有该类的超类,那么查询将表明所涉及的类没有这样的注释。<p>注意,这个元注释类型没有效果,如果注释的类型是用来注释类以外的任何东西。还要注意,这个元注释只会导致从超类继承注释;对实现接口的注释没有效果

3.jdk8新特性

1.可重复注解

一个类上写两个一样的注解

  1. @MyAnnotation("hi")
  2. @MyAnnotation
  3. public class AnnotationTest {
  4. }
  5. @Retention(RetentionPolicy.RUNTIME)//运行时
  6. //指定可以修饰哪些结构
  7. @Target(value = {ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD,
  8. ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE,
  9. ElementType.PARAMETER, ElementType.TYPE, ElementType.TYPE_PARAMETER,
  10. ElementType.TYPE_USE})
  11. @Documented//文档注释保留识别
  12. @Inherited//被子类继承
  13. @Repeatable(MyAnnotations.class)//标识该注解可以实现重复注解
  14. public @interface MyAnnotation {
  15. String value() default "hello";
  16. //String类型的属性,默认值为hello
  17. }
  18. @Retention(RetentionPolicy.RUNTIME)//运行时
  19. //指定可以修饰哪些结构
  20. @Target(value = {ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD,
  21. ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE,
  22. ElementType.PARAMETER, ElementType.TYPE, ElementType.TYPE_PARAMETER,
  23. ElementType.TYPE_USE})
  24. @Documented//文档注释保留识别
  25. @Inherited//被子类继承
  26. public @interface MyAnnotations {
  27. //声明一个MyAnnotation类型的数组
  28. MyAnnotation []value();
  29. }

2.类型注解

  1. class Test<@MyAnnotation T> {
  2. }
  3. //此时需要指明@Target(ElementType.TYPE_PARAMETER)
  1. class Test2{
  2. public static void main(String[] args) {
  3. Class<Test> clazz = Test.class;
  4. Annotation[] annotations = clazz.getAnnotations();
  5. for (int i = 0; i <annotations.length ; i++) {
  6. System.out.println(annotations[i]);
  7. }
  8. }
  9. }

九,集合框架

1.collection接口

1)Java集合框架的概述

  1. 1.集合和数组都是对多个数据进行存储操作的结构,简称Java容器。
  2. 说明:此时的存储时内存方面的存储,不涉及持久化存储
  3. 2.1数组在存储多个数据方面的特点:
  4. 1)一旦初始化以后,长度就确定了。
  5. 2)元素类型一旦指定,就不能改变,我们就只能操作指定类型的数据。
  6. 2.2数组在存取数据方面的缺点:
  7. 1)初始化以后,长度不可修改。
  8. 2)数组中提供的方法非常有限,对于删除插入数据非常不方便,效率也不高。
  9. 3)获取数组中实际元素的个数,数组并没有提供现成的方法。
  10. 4)数组存储数据的特点:有序,可重复。

集合框架

  1. Collection接口:单列集合,用来存储一个一个对象
  2. list接口:有序的可重复的数据。“动态数组”
  3. Set接口:无序的不可重复的数据。
  4. Map接口:双列集合,用来存储一对一对的数据。(key,value)

Collection接口中的方法的使用

  1. public static void main(String[] args) {
  2. Collection collection=new ArrayList();
  3. collection.add("aa");//将元素添加到集合中
  4. collection.add("bb");
  5. collection.add("cc");
  6. System.out.println(collection.size());//获取添加的元素的个数
  7. Collection collection2=new ArrayList();
  8. collection2.add("bbb");
  9. collection2.add("ccc");
  10. collection.addAll(collection2);//将一个集合的元素添加到另一个集合
  11. System.out.println(collection.size());
  12. System.out.println(collection);//输出集合
  13. collection2.clear();//清空集合中的元素
  14. System.out.println(collection.isEmpty());//判断当前集合是否为空 true false
  15. }
  1. public static void main(String[] args) {
  2. Collection collection=new ArrayList();
  3. collection.add(123);
  4. collection.add("tom");
  5. collection.add("aa");
  6. Person p1=new Person("dong",23);
  7. collection.add(p1);
  8. /**
  9. * 集合中添加对象,最好重写该对象所在类的equals(方法
  10. */
  11. System.out.println(collection.contains(p1));//判断当前集合是否包含该元素,使用Obj对象所在类的equals(方法。
  12. collection.containsAll(collection);//判断形参集合中的所元素是否都在该集合中。
  13. collection.remove(p1);//移除某个元素 boolean返回true/false
  14. collection.removeAll(collection);//从当前集合移除两者都的元素
  15. collection.retainAll(collection);//获取当前集合和形参集合的交集,并返回当前集合。
  16. collection.equals(collection);//比较两个集合是否完全相同
  17. }
  1. public static void main(String[] args) {
  2. Collection collection=new ArrayList();
  3. collection.add("123");
  4. collection.add("aaa");
  5. collection.add("bbbb");
  6. collection.add("dddd");
  7. System.out.println(collection.hashCode());//输出hash值
  8. collection.toArray();//集合-->数组
  9. //数组-->集合Arrays.asList();
  10. //iterator返回这个接口的实例,用于遍历集合元素。
  11. }

使用Iterator遍历Colllection集合

  • Collection集合实现了Iterator接口,重写了接口的hasNext()和next()方法。
  • 内部定义了remove()方法,可以在便利的时候,删除集合中的元素,
    此方法不同于集合直接调用remove().
  1. public static void main(String[] args) {
  2. Collection co=new ArrayList();
  3. co.add("123113212");
  4. co.add("456487874");
  5. co.add("56646665454654");
  6. Iterator<Collection>iterator=co.iterator();
  7. while (iterator.hasNext()){
  8. // if (iterator.next().equals("Tom")){
  9. // iterator.remove();
  10. // }
  11. System.out.println(iterator.next());
  12. }
  13. }

增强for循环遍历集合

  • 内部仍然调用了迭代器

  • 把集合中的每个值一次一次赋值给Object类型的变量然后输出

    1. public static void main(String[] args) {
    2. Collection co=new ArrayList();
    3. co.add("123113212");
    4. co.add("456487874");
    5. co.add("56646665454654");
    6. for (Object c:co){
    7. System.out.println(c);
    8. }
    9. }

Collection集合接口是支持泛型的,并且继承了Iterable接口,可以使用Iterator iterator()进行遍历

  1. * @see Set
  2. * @see List
  3. * @see Map
  4. * @see SortedSet
  5. * @see SortedMap
  6. * @see HashSet
  7. * @see TreeSet
  8. * @see ArrayList
  9. * @see LinkedList
  10. * @see Vector
  11. * @see Collections
  12. * @see Arrays
  13. * @see AbstractCollection
  14. * @since 1.2
  15. */
  16. public interface Collection<E> extends Iterable<E> {
  17. public interface Iterable<T> {
  18. /**
  19. * Returns an iterator over elements of type {@code T}.
  20. *
  21. * @return an Iterator.
  22. */
  23. Iterator<T> iterator();

2)list

比较ArrayList,LinkedList,Vector

  1. * 同:三个类都实现了list接口,存储数据的特点相同,有序,可重复。
  2. * ArrayList:作为list接口的主要实现类,jdk1.2,线程不安全的,效率高,底层使用Object []elementData存储
  3. * LinkedList:jdk1.2:底层使用双向链表存储,对于频繁的插入删除,他的效率高。
  4. * Vector:古老的实现类jdk1.0,线程安全的。

List接口常用方法测试:

  1. public static void main(String[] args) {
  2. ArrayList<Object> list = new ArrayList<>();
  3. list.add("123");
  4. list.add("456");
  5. list.add("789");
  6. System.out.println(list);//[123, 456, 789]
  7. list.add(0,"000");//指定位置插入
  8. System.out.println(list);//[000, 123, 456, 789]
  9. List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 6);//数组转化为集合
  10. list.addAll(list1);//将集合list1添加进集合list
  11. System.out.println(list.size());//输出集合多少个元素 10
  12. Object o = list.get(0);//通过索引获取元素
  13. System.out.println(o);//000
  14. int index = list.indexOf("456");//查找元素的索引.如果不存在返回-1
  15. System.out.println(index);//2
  16. Object o1 = list.remove(1);//可以照索引或者对象删除
  17. System.out.println(o1+" "+list);//123 [000, 456, 789, 1, 2, 3, 4, 5, 6]
  18. list.set(1,"cc");//将某个索引的值改为
  19. List<Object> list2 = list.subList(1, 5);//截取集合中的元素
  20. System.out.println(list2);//[cc, 789, 1, 2]
  21. }

List遍历,及方法总结

  1. public static void main(String[] args) {
  2. ArrayList<Object> list = new ArrayList<>();
  3. list.add("123");
  4. list.add("456");
  5. list.add("789");
  6. //1.Iterator
  7. Iterator<Object> iterator = list.iterator();
  8. while (iterator.hasNext()){
  9. System.out.println(iterator.next());
  10. }
  11. //2.增强for循环
  12. for (Object obj:list){
  13. System.out.println(obj);
  14. }
  15. //3..普通for循环
  16. for (int i=0;i<list.size();i++){
  17. System.out.println(list.get(i));
  18. }
  19. }

List的一道面试题

  1. public static void main(String[] args) {
  2. List list=new ArrayList<>();
  3. list.add(1);
  4. list.add(2);
  5. list.add(3);
  6. updatelist(list);
  7. System.out.println(list);//[1, 2]
  8. }
  9. private static void updatelist(List list) {
  10. list.remove(2);
  11. // list.remove(new Integer(2));//如果想删除元素2
  12. }

jdk 1.2的接口

继承了Collection接口

sort方法需要传入一个比较器

定制排序

实际上使用了Arrays的sort方法

  1. public interface List<E> extends Collection<E> {
  2. default void sort(Comparator<? super E> c) {
  3. Object[] a = this.toArray();
  4. Arrays.sort(a, (Comparator) c);
  5. ListIterator<E> i = this.listIterator();
  6. for (Object e : a) {
  7. i.next();
  8. i.set((E) e);
  9. }
  10. }

ArrayList源码分析:

  1. /*
  2. * jdk7:
  3. * ArrayList list=new ArrayList()//底层创建了长度是10的Object[]elementDate数组
  4. * list.add(123);//elementData[0]=new Integer(123);
  5. * ...
  6. * list.add();//如果此次的添加导致底层的数组容量不够,则扩容。
  7. * 默认情况下,扩容为原来的1.5倍,同时需要将原有数组的数据复制到新的数组。
  8. * 结论:建议开发中使用带参数的构造器:ArrayList list=new ArrayList(int 数组长度);
  9. * jdk8:
  10. * ArrayList list=new ArrayList()//底层Object[]elementDate={},并没有创建长度为10的数组
  11. * list.add(123);//第一次调用add时,底层才创建了长度为10的数组,并将数据123添加到elementData[0]
  12. * ...后续的添加和扩容操作与jdk7无异。
  13. * 对比:jdk7中的对象创建类似于单例的饿汉式,而jdk8中的对象的创建类似于单例的懒汉式,
  14. * 延迟了数组的创建,节省内存空间。
  15. */
  1. public class ArrayList<E> extends AbstractList<E>
  2. implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
  3. //默认初始容量为10
  4. private static final int DEFAULT_CAPACITY = 10;
  5. //空的ElementData数组
  6. private static final Object[] EMPTY_ELEMENTDATA = {};
  7. //用于默认大小的空实例。我们从空的ELEMENTDATA中解出这个问题,以了解在添加第一个元素时应该增加多少
  8. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  9. //存储ArrayList的元素的数组缓冲区。arraylisis的容量是这个数组缓冲区的长度。当添加第一个元素时,任何带有elementData DBEAULTCAPACITY empty ELEMENTDATE的空ArrayList都将被扩展为默认容量(10)
  10. transient Object[] elementData;
  11. //带有指定长度的数组构造器
  12. public ArrayList(int initialCapacity) {
  13. if (initialCapacity > 0) {
  14. this.elementData = new Object[initialCapacity];
  15. } else if (initialCapacity == 0) {
  16. this.elementData = EMPTY_ELEMENTDATA;
  17. } else {
  18. throw new IllegalArgumentException("Illegal Capacity: "+
  19. initialCapacity);
  20. }
  21. }
  22. //传入一个Collection类型的构造器
  23. public ArrayList(Collection<? extends E> c) {
  24. elementData = c.toArray();
  25. if ((size = elementData.length) != 0) {
  26. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  27. if (elementData.getClass() != Object[].class)
  28. elementData = Arrays.copyOf(elementData, size, Object[].class);
  29. } else {
  30. // replace with empty array.
  31. this.elementData = EMPTY_ELEMENTDATA;
  32. }
  33. }
  34. //将这个<tt>ArrayList</tt>实例的容量调整为列表的当前大小。集合创建的时候会流出来预留的空间,使用这个方法可以去掉预留空间,节省内存。
  35. public void trimToSize() {
  36. modCount++;
  37. if (size < elementData.length) {
  38. elementData = (size == 0)
  39. ? EMPTY_ELEMENTDATA
  40. : Arrays.copyOf(elementData, size);
  41. }
  42. }
  43. //设置数组的最大长度为integer的最大值-8,防止造成内存溢出异常
  44. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  45. //数组的扩容问题:>>1意思就是/2
  46. private void grow(int minCapacity) {
  47. // overflow-conscious code
  48. //扩容前数组的长度
  49. int oldCapacity = elementData.length;
  50. //新数组扩容为原来的1.5倍
  51. int newCapacity = oldCapacity + (oldCapacity >> 1);
  52. //如果扩容前比扩容后小
  53. if (newCapacity - minCapacity < 0)
  54. //还是原来的数组
  55. newCapacity = minCapacity;
  56. //如果扩容后超出数组的最大值
  57. if (newCapacity - MAX_ARRAY_SIZE > 0)
  58. //数组长度变为数组的最大长度
  59. newCapacity = hugeCapacity(minCapacity);
  60. //将原来的数组在复制进新的数组
  61. elementData = Arrays.copyOf(elementData, newCapacity);
  62. }
  63. //在列表中指定的位置插入指定的元素。将当前位于该位置的元素(如果有)和任何后续元素右移一位(将一个元素添加到它们的索引中)
  64. public void add(int index, E element) {
  65. rangeCheckForAdd(index);
  66. ensureCapacityInternal(size + 1); // Increments modCount!!
  67. System.arraycopy(elementData, index, elementData, index + 1,
  68. size - index);
  69. elementData[index] = element;
  70. size++;
  71. }
  72. //底层重写了sort方法
  73. @Override
  74. @SuppressWarnings("unchecked")
  75. public void sort(Comparator<? super E> c) {
  76. //记录集合的修改次数
  77. final int expectedModCount = modCount;
  78. //排序
  79. Arrays.sort((E[]) elementData, 0, size, c);
  80. if (modCount != expectedModCount) {//应该是多线程考虑
  81. throw new ConcurrentModificationException();
  82. }
  83. modCount++;
  84. }

LinkedList源码分析

  1. /**
  2. *LinkedList list=new LinkedList();//内部声明了Node类型的first和last属性,默认值为null
  3. * list.add(123);//将123封装到了node中,创建了Node对象。
  4. * 其中,Node定义为:体现了LinkedList双向链表的说法。
  5. */
  6. private static class Node<E> {
  7. E item;
  8. Node<E> next;
  9. Node<E> prev;
  10. Node(Node<E> prev, E element, Node<E> next) {
  11. this.item = element;
  12. this.next = next;
  13. this.prev = prev;
  14. }
  15. }

jdk1.2

实现了List接口,Deque,Cloneable, java.io.Serializable

Deque

线性集合,支持两端插入和移除元素。 名称deque是“双端队列”的缩写

Cloneable

cloneable其实就是一个标记接口,只有实现这个接口后,然后在类中重写Object中的clone方法,然后通过类调用clone方法才能克隆成功,如果不实现这个接口,则会抛出CloneNotSupportedException(克隆不被支持)异常。

java.io.Serializable

支持序列化

  1. public class LinkedList<E>
  2. extends AbstractSequentialList<E>
  3. implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  4. {
  5. //指向第一个节点的指针
  6. transient Node<E> first;
  7. //指向最后一个节点的指针
  8. transient Node<E> last;
  9. //LinkedList的数据结构就是双向链表
  10. private static class Node<E> {
  11. E item;//数据元素
  12. Node<E> next;//后继节点
  13. Node<E> prev;//前驱节点
  14. Node(Node<E> prev, E element, Node<E> next) {
  15. this.item = element;
  16. this.next = next;
  17. this.prev = prev;
  18. }
  19. }
  20. //构造器
  21. transient int size = 0;//数据个数
  22. transient Node<E> first;//表示链表的第一个节点
  23. transient Node<E> last;//表示链表的最后一个节点
  24. public LinkedList() {
  25. }
  26. public LinkedList(Collection<? extends E> c) {//用于整合Collection类型的数据
  27. this();
  28. addAll(c);
  29. }
  30. //add:
  31. public boolean add(E e) {
  32. linkLast(e);
  33. return true;
  34. }
  35. void linkLast(E e) {//采用的是尾插法
  36. final Node<E> l = last;
  37. final Node<E> newNode = new Node<>(l, e, null);//新节点的前驱指向last的地址,后继为null,
  38.                                 //所以说这是一个双向链表,但不是循环的,循环的话,后继指向头节点
  39. last = newNode;//让last指向新节点,也就说这个新节点是链表的最后一个元素
  40. if (l == null)//当第一次添加时,first,last都是null,如果last是null,表明这是一个空链表
  41. first = newNode;//就让新节点指向first,现在first和last都是同一个节点
  42. else
  43. l.next = newNode;//当在添加数据时,就让老链表的最后一个节点的后继指向新节点(那个节点本来是null的)
  44. size++; //长度加1
  45. modCount++;
  46. /**
  47. 总结:
  48. 新建一个节点,让新节点的前驱指向老链表的最后一个节点
  49. 让老链表的最后一个节点的后继指向新节点
  50. 让新节点变成链表的最后一个节点
  51. 长度加1
  52. 第一个节点前驱为null,最后一个节点后继为null
  53. */
  54. }
  55. //get
  56. public E get(int index) {
  57. checkElementIndex(index);//检查一下索引是否在0到size的范围内
  58. return node(index).item;
  59. }
  60. Node<E> node(int index) {
  61. // assert isElementIndex(index);
  62. if (index < (size >> 1)) {//看看索引的位置是在链表的前半部分还是后半部分,决定正着搜索或倒着搜索,找到后返回就行啦
  63. Node<E> x = first;
  64. for (int i = 0; i < index; i++)//在这里看到链表是从0开始的
  65. x = x.next;
  66. return x;
  67. } else {
  68. Node<E> x = last;
  69. for (int i = size - 1; i > index; i--)
  70. x = x.prev;
  71. return x;
  72. }
  73. }
  74. //remove
  75. public E remove(int index) {
  76. checkElementIndex(index);//先检查一下索引
  77. return unlink(node(index));
  78. }
  79. //先拿着索引找到这个节点
  80. E unlink(Node<E> x) {
  81. // assert x != null;
  82. final E element = x.item;//节点的元素
  83. final Node<E> next = x.next;//节点的后继
  84. final Node<E> prev = x.prev;//节点的前驱
  85. if (prev == null) {
  86. first = next;
  87. } else {
  88. prev.next = next;
  89. x.prev = null;
  90. }
  91. if (next == null) {
  92. last = prev;
  93. } else {
  94. next.prev = prev;
  95. x.next = null;
  96. }
  97. x.item = null;
  98. size--;
  99. modCount++;
  100. return element;
  101. }

Vector源码分析

先创建初始长度为十的数组,扩容默认为原来的二倍,线程安全的。

Vector 是矢量队列,底层是数组。它是JDK1.0版本添加的类。继承于AbstractList,实现了List, RandomAccess, Cloneable

Vector 继承了AbstractList,实现了List;所以,它是一个队列,支持相关的添加、删除、修改、遍历等功能。
Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。
Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。
Vector中的操作是线程安全的。因为Vector的方法前加了synchronized 关键字,所以效率不高。

  1. public class Vector<E>
  2. extends AbstractList<E>
  3. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  4. {
  5. //向量的分量所在的数组缓冲区存储。向量的容量是这个数组缓冲区的长度,并且至少大到可以包含向量的所有元素。
  6. protected Object[] elementData;
  7. //这个对象有效组件的数量
  8. protected int elementCount;
  9. //当向量的大小大于其容量时,该向量的容量自动增加的量。如果容量增量小于或等于0,则每次需要增长时,向量的容量将增加一倍。
  10. protected int capacityIncrement;
  11. //用指定的初始容量和容量增量构造一个空向量。@paraminitialCapacity向量的初始容量@paramcapacitylncrement容量所占的量当向量溢出@抛出illeqalarqumentexceptionifspecifiedinitialcapacity时增加是负的
  12. public Vector(int initialCapacity, int capacityIncrement) {
  13. super();
  14. if (initialCapacity < 0)
  15. throw new IllegalArgumentException("Illegal Capacity: "+
  16. initialCapacity);
  17. this.elementData = new Object[initialCapacity];
  18. this.capacityIncrement = capacityIncrement;
  19. }
  20. //默认增量为0
  21. public Vector(int initialCapacity) {
  22. this(initialCapacity, 0);
  23. }
  24. //默认长度为10
  25. public Vector() {
  26. this(10);
  27. }
  28. //扩容方法
  29. //@param minCapacity the desired minimum capacity 所需要的最低容量
  30. 如果最低容量>0,记录集合又被修改一次
  31. 调用ensureCapacityHelper(minCapacity)方法
  32. public synchronized void ensureCapacity(int minCapacity) {
  33. if (minCapacity > 0) {
  34. modCount++;
  35. ensureCapacityHelper(minCapacity);
  36. }
  37. }
  38. //接下来,进入ensureCapacityHelper(minCapacity)方法
  39. private void ensureCapacityHelper(int minCapacity) {
  40. // overflow-conscious code
  41. 如果指定的扩容后长度比现在的容量大,说明扩容是合法的
  42. 调用grow(minCapacity)方法
  43. if (minCapacity - elementData.length > 0)
  44. grow(minCapacity);
  45. }
  46. //继续点击,进入grow(minCapacity)
  47. private void grow(int minCapacity) {
  48. // overflow-conscious code
  49. int oldCapacity = elementData.length;//用来记录原长度
  50. //新的长度的计算:如果增长的长度大于0就扩容为原来的长度+新增的长度,否则扩容为原来的2倍
  51. int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
  52. capacityIncrement : oldCapacity);
  53. if (newCapacity - minCapacity < 0)
  54. //如果闲的容量比所需要的最低容量小,新的长度就等于所需的最低容量
  55. newCapacity = minCapacity;
  56. if (newCapacity - MAX_ARRAY_SIZE > 0)
  57. //如果超出最大临界值,就让新数组长度等于最大临界值
  58. newCapacity = hugeCapacity(minCapacity);
  59. //将原来的元素复制进来
  60. elementData = Arrays.copyOf(elementData, newCapacity);
  61. }

3)set

  1. /**
  2. * 1.Set接口的框架结构:存储无顺序的,不可重复的数据。
  3. * HashSet:作为set接口的主要实现类,线程不安全,可以存储null
  4. *
  5. * LinkedHashSet:HashSet的子类。遍历其内部数据时,可以按照添加的顺序遍历。
  6. *
  7. * TreeSet:可以按照添加对象的指定属性,进行排序。
  8. *
  9. * 2.如何理解Set的无序,不可重复。
  10. * ①无序性:不等于随机性。
  11. *以hashset为例,存储的数据在底层数组中并非按照数组索引的顺序添加,而是根据数据的哈希值添加。
  12. * ②不可重复性:保证添加的元素按照equals()方法判断时,不能返回True。即,相同的元素只能添加一个。
  13. * hashset底层为数组加链表
  14. * 3.Set接口中没有额外定义新的方法,使用的都是Collection接口中声明过的方法。
  15. * 4.添加元素的过程:以HashSet为例
  16. * 我们想hashset中添加元素a,首先调用a所在类的hashcode方法,计算a的哈希值,
  17. * 此哈希值通过算法计算中在hashset底层数组的存放位置,判断数组此位置是否已经有元素,
  18. * 如果此位置上没有其他元素,a直接添加成功;如果此位置有其他元素b(或以链表形式存在多个元素),
  19. * 则比较a和b的哈希值,如果哈希值不相同,则,元素a添加成功,如果哈希值相同,调用元素a所在类的equals()
  20. * 方法,equals()返回true,元素添加失败,如果返回false,元素a添加成功。
  21. * 说明/:对于添加的位置有元素还添加成功的情况,与已经存在位置上数据以链表形式存储,
  22. * jdk7中a放到数组中,指向原来的元素,jdk8中原来的元素放在数组中,指向a元素。
  23. * 5.要求:
  24. * ①向set中添加的数据,其所在的类一定要重写hashCode()和equals()方法
  25. * ②重写hashCode()和equals()方法尽可能保持一致:相等的对象哈希值必须相同。
  26. */
  1. public interface Spliterator<T> {
  2. Spliterator(splitable iterator可分割迭代器)接口是Java为了并行遍历数据源中的元素而设计的迭代器,这个可以类比最早Java提供的顺序遍历迭代器Iterator,但一个是顺序遍历,一个是并行遍历
  1. public interface Set<E> extends Collection<E> {
  2. //证明了set集合不可重复
  3. @Override
  4. default Spliterator<E> spliterator() {
  5. return Spliterators.spliterator(this, Spliterator.DISTINCT);
  6. }

面试题

  1. /**
  2. * 面试题一:在list内去除重复数据值,
  3. */
  4. public static void main(String[] args) {
  5. ArrayList<String> list = new ArrayList<>();
  6. list.add("123");
  7. list.add("456");
  8. list.add("789");
  9. list.add("456");
  10. List list2=quChong(list);
  11. Iterator<String> iterator = list2.iterator();
  12. while (iterator.hasNext()){
  13. System.out.println(iterator.next ());
  14. }
  15. }
  16. public static List<String> quChong(List list){
  17. HashSet<String> set = new HashSet<>();
  18. set.addAll(list);
  19. return new ArrayList(set);
  20. }

HashSet

  1. /*
  2. * 我们想hashset中添加元素a,首先调用a所在类的hashcode方法,计算a的哈希值,
  3. * 此哈希值通过算法计算中在hashset底层数组的存放位置,判断数组此位置是否已经有元素,
  4. * 如果此位置上没有其他元素,a直接添加成功;如果此位置有其他元素b(或以链表形式存在多个元素),
  5. * 则比较a和b的哈希值,如果哈希值不相同,则,元素a添加成功,如果哈希值相同,调用元素a所在类的equals()
  6. * 方法,equals()返回true,元素添加失败,如果返回false,元素a添加成功。
  7. * 说明/:对于添加的位置有元素还添加成功的情况,与已经存在位置上数据以链表形式存储,
  8. * jdk7中a放到数组中,指向原来的元素,jdk8中原来的元素放在数组中,指向a元素。
  9. */

继承了AbstractSet

实现了Set, Cloneable, java.io.Serializable

AbstractSet

  1. public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
  2. 里面写了equals hashcode removeAll方法
  1. public class HashSet<E>
  2. extends AbstractSet<E>
  3. implements Set<E>, Cloneable, java.io.Serializable
  4. {
  5. static final long serialVersionUID = -5024744406713321676L;
  6. // 底层使用HashMap来保存HashSet中所有元素。
  7. private transient HashMap<E,Object> map;
  8. // 定义一个虚拟的Object对象作为HashMap的value,将此对象定义为static final。
  9. private static final Object PRESENT = new Object();
  10. //关于为什么不用null而是用一个Object类型的对象,因为map的key本身是可以为null的,二set存储元素成功与否
  11. 是需要返回一个true或者false,如果使用null来充当value,你就不知道到底存储成功没
  12. /**
  13. * 默认的无参构造器,构造一个空的HashSet。
  14. *
  15. * 实际底层会初始化一个空的HashMap,并使用默认初始容量为16和加载因子0.75。
  16. */
  17. public HashSet() {
  18. map = new HashMap<E,Object>();
  19. }
  20. /**
  21. * 构造一个包含指定collection中的元素的新set。
  22. *
  23. * 实际底层使用默认的加载因子0.75和足以包含指定
  24. * collection中所有元素的初始容量来创建一个HashMap。
  25. * @param c 其中的元素将存放在此set中的collection。
  26. */
  27. public HashSet(Collection<? extends E> c) {
  28. map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));
  29. addAll(c);
  30. }
  31. /**
  32. * 以指定的initialCapacity和loadFactor构造一个空的HashSet。
  33. *
  34. * 实际底层以相应的参数构造一个空的HashMap。
  35. * @param initialCapacity 初始容量。
  36. * @param loadFactor 加载因子。
  37. */
  38. public HashSet(int initialCapacity, float loadFactor) {
  39. map = new HashMap<E,Object>(initialCapacity, loadFactor);
  40. }
  41. /**
  42. * 以指定的initialCapacity构造一个空的HashSet。
  43. *
  44. * 实际底层以相应的参数及加载因子loadFactor为0.75构造一个空的HashMap。
  45. * @param initialCapacity 初始容量。
  46. */
  47. public HashSet(int initialCapacity) {
  48. map = new HashMap<E,Object>(initialCapacity);
  49. }
  50. /**
  51. * 以指定的initialCapacity和loadFactor构造一个新的空链接哈希集合。
  52. * 此构造函数为包访问权限,不对外公开,实际只是是对LinkedHashSet的支持。
  53. *
  54. * 实际底层会以指定的参数构造一个空LinkedHashMap实例来实现。
  55. * @param initialCapacity 初始容量。
  56. * @param loadFactor 加载因子。
  57. * @param dummy 标记。
  58. */
  59. HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  60. map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
  61. }
  62. /**
  63. * 返回对此set中元素进行迭代的迭代器。返回元素的顺序并不是特定的。
  64. *
  65. * 底层实际调用底层HashMap的keySet来返回所有的key。
  66. * 可见HashSet中的元素,只是存放在了底层HashMap的key上,
  67. * value使用一个static final的Object对象标识。
  68. * @return 对此set中元素进行迭代的Iterator。
  69. */
  70. public Iterator<E> iterator() {
  71. return map.keySet().iterator();
  72. }
  73. /**
  74. * 返回此set中的元素的数量(set的容量)。
  75. *
  76. * 底层实际调用HashMap的size()方法返回Entry的数量,就得到该Set中元素的个数。
  77. * @return 此set中的元素的数量(set的容量)。
  78. */
  79. public int size() {
  80. return map.size();
  81. }
  82. /**
  83. * 如果此set不包含任何元素,则返回true。
  84. *
  85. * 底层实际调用HashMap的isEmpty()判断该HashSet是否为空。
  86. * @return 如果此set不包含任何元素,则返回true。
  87. */
  88. public boolean isEmpty() {
  89. return map.isEmpty();
  90. }
  91. /**
  92. * 如果此set包含指定元素,则返回true。
  93. * 更确切地讲,当且仅当此set包含一个满足(o==null ? e==null : o.equals(e))
  94. * 的e元素时,返回true。
  95. *
  96. * 底层实际调用HashMap的containsKey判断是否包含指定key。
  97. * @param o 在此set中的存在已得到测试的元素。
  98. * @return 如果此set包含指定元素,则返回true。
  99. */
  100. public boolean contains(Object o) {
  101. return map.containsKey(o);
  102. }
  103. /**
  104. * 如果此set中尚未包含指定元素,则添加指定元素。
  105. * 更确切地讲,如果此 set 没有包含满足(e==null ? e2==null : e.equals(e2))
  106. * 的元素e2,则向此set 添加指定的元素e。
  107. * 如果此set已包含该元素,则该调用不更改set并返回false。
  108. *
  109. * 底层实际将将该元素作为key放入HashMap。
  110. * 由于HashMap的put()方法添加key-value对时,当新放入HashMap的Entry中key
  111. * 与集合中原有Entry的key相同(hashCode()返回值相等,通过equals比较也返回true),
  112. * 新添加的Entry的value会将覆盖原来Entry的value,但key不会有任何改变,
  113. * 因此如果向HashSet中添加一个已经存在的元素时,新添加的集合元素将不会被放入HashMap中,
  114. * 原来的元素也不会有任何改变,这也就满足了Set中元素不重复的特性。
  115. * @param e 将添加到此set中的元素。
  116. * @return 如果此set尚未包含指定元素,则返回true。
  117. */
  118. public boolean add(E e) {
  119. return map.put(e, PRESENT)==null;
  120. }
  121. /**
  122. * 如果指定元素存在于此set中,则将其移除。
  123. * 更确切地讲,如果此set包含一个满足(o==null ? e==null : o.equals(e))的元素e,
  124. * 则将其移除。如果此set已包含该元素,则返回true
  125. * (或者:如果此set因调用而发生更改,则返回true)。(一旦调用返回,则此set不再包含该元素)。
  126. *
  127. * 底层实际调用HashMap的remove方法删除指定Entry。
  128. * @param o 如果存在于此set中则需要将其移除的对象。
  129. * @return 如果set包含指定元素,则返回true。
  130. */
  131. public boolean remove(Object o) {
  132. return map.remove(o)==PRESENT;
  133. }
  134. /**
  135. * 从此set中移除所有元素。此调用返回后,该set将为空。
  136. *
  137. * 底层实际调用HashMap的clear方法清空Entry中所有元素。
  138. */
  139. public void clear() {
  140. map.clear();
  141. }
  142. /**
  143. * 返回此HashSet实例的浅表副本:并没有复制这些元素本身。
  144. *
  145. * 底层实际调用HashMap的clone()方法,获取HashMap的浅表副本,并设置到HashSet中。
  146. */
  147. public Object clone() {
  148. try {
  149. HashSet<E> newSet = (HashSet<E>) super.clone();
  150. newSet.map = (HashMap<E, Object>) map.clone();
  151. return newSet;
  152. } catch (CloneNotSupportedException e) {
  153. throw new InternalError();
  154. }
  155. }
  156. }

LinkedHashSet

  1. /*
  2. * LinkedHashSet的使用
  3. * LinkedHashSet作为hashSet的子类,再添加数据的同时,每个数据还维护了一对双向链表,
  4. * 记录此数据的前一个数据和后一个数据。对于频繁的遍历,LinkedHashSet的效率高于HashSet
  5. */
  1. public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, java.io.Serializable {
  2. LinkHashSet底层只是单纯的继承了HashSet并没啥太大改变

TreeSet的使用

  1. public class TreeSet<E> extends AbstractSet<E>
  2. implements NavigableSet<E>, Cloneable, java.io.Serializable
  3. {
  4. /**
  5. * 可以排序的map.
  6. */
  7. private transient NavigableMap<E,Object> m;
  8. // 用来存入map的value的
  9. private static final Object PRESENT = new Object();
  10. /**
  11. * 构造一个指定map集合的TreeSet
  12. */
  13. TreeSet(NavigableMap<E,Object> m) {
  14. this.m = m;
  15. }
  16. //自然排序
  17. 构造一个新的空树集,根据其元素的自然顺序排序。所有插入到集合中的元素必须实现{@link comparable}接口。此外,所有这些元素都必须<我>相互可比< / ix: f@code e1.compareTo (e2)}不能抛出一个f@code ClassCastException} {@code el}对任何元素集和f@code e2}。如果用户试图添加一个字符串进入Integer类型的Set{@code添加}调用将抛出一个
  18. public TreeSet() {
  19. this(new TreeMap<E,Object>());
  20. }
  21. /**
  22. 定制排序
  23. * Constructs a new, empty tree set, sorted according to the specified
  24. * comparator. All elements inserted into the set must be <i>mutually
  25. * comparable</i> by the specified comparator: {@code comparator.compare(e1,
  26. * e2)} must not throw a {@code ClassCastException} for any elements
  27. * {@code e1} and {@code e2} in the set. If the user attempts to add
  28. * an element to the set that violates this constraint, the
  29. * {@code add} call will throw a {@code ClassCastException}.
  30. *
  31. * @param comparator the comparator that will be used to order this set.
  32. * If {@code null}, the {@linkplain Comparable natural
  33. * ordering} of the elements will be used.
  34. */
  35. public TreeSet(Comparator<? super E> comparator) {
  36. this(new TreeMap<>(comparator));
  37. }
  38. /**
  39. * Constructs a new tree set containing the elements in the specified
  40. * collection, sorted according to the <i>natural ordering</i> of its
  41. * elements. All elements inserted into the set must implement the
  42. * {@link Comparable} interface. Furthermore, all such elements must be
  43. * <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a
  44. * {@code ClassCastException} for any elements {@code e1} and
  45. * {@code e2} in the set.
  46. *
  47. * @param c collection whose elements will comprise the new set
  48. * @throws ClassCastException if the elements in {@code c} are
  49. * not {@link Comparable}, or are not mutually comparable
  50. * @throws NullPointerException if the specified collection is null
  51. */
  52. public TreeSet(Collection<? extends E> c) {
  53. this();
  54. addAll(c);
  55. }
  56. /**
  57. * Constructs a new tree set containing the same elements and
  58. * using the same ordering as the specified sorted set.
  59. *
  60. * @param s sorted set whose elements will comprise the new set
  61. * @throws NullPointerException if the specified sorted set is null
  62. */
  63. public TreeSet(SortedSet<E> s) {
  64. this(s.comparator());
  65. addAll(s);
  66. }
  67. /**
  68. * Returns an iterator over the elements in this set in ascending order.
  69. *以升序返回此集合中元素的迭代器。
  70. * @return an iterator over the elements in this set in ascending order
  71. */
  72. public Iterator<E> iterator() {
  73. return m.navigableKeySet().iterator();
  74. }
  75. /**
  76. * Returns an iterator over the elements in this set in descending order.
  77. *按降序返回该集合中元素的迭代器。
  78. * @return an iterator over the elements in this set in descending order
  79. * @since 1.6
  80. */
  81. public Iterator<E> descendingIterator() {
  82. return m.descendingKeySet().iterator();
  83. }
  84. /**
  85. * @since 1.6
  86. */
  87. public NavigableSet<E> descendingSet() {
  88. return new TreeSet<>(m.descendingMap());
  89. }
  90. public int size() {
  91. return m.size();
  92. }
  93. public boolean isEmpty() {
  94. return m.isEmpty();
  95. }
  96. public boolean contains(Object o) {
  97. return m.containsKey(o);
  98. }
  99. /**
  100. * Adds the specified element to this set if it is not already present.
  101. * More formally, adds the specified element {@code e} to this set if
  102. * the set contains no element {@code e2} such that
  103. * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
  104. * If this set already contains the element, the call leaves the set
  105. * unchanged and returns {@code false}.
  106. *大概意思就是先根据hash值比交,不相同直接添加成功,
  107. hashcode相同在判断是不是null然后调用equals方法进行比较
  108. equals方法返回true,则添加失败,否则添加成功。
  109. * @param e element to be added to this set
  110. * @return {@code true} if this set did not already contain the specified
  111. * element
  112. * @throws ClassCastException if the specified object cannot be compared
  113. * with the elements currently in this set
  114. * @throws NullPointerException if the specified element is null
  115. * and this set uses natural ordering, or its comparator
  116. * does not permit null elements
  117. */
  118. public boolean add(E e) {
  119. return m.put(e, PRESENT)==null;
  120. }
  121. 如果指定的元素存在,则从该集合中移除它。更正式的说法是,删除元素f@code e}< (ttx - o = null&nbsp;? e = -null&nbsp &nbsp;;o.equals &nbsp; (e)) / tt >、<如果这个集合包含这样一个元素。如果该集合包含元素,则返回{@code true}(或者,如果该集合由于调用而改变,则返回相等的结果)。(一旦调用返回,这个集合将不包含元素。)
  122. * @param o object to be removed from this set, if present
  123. * @return {@code true} if this set contained the specified element
  124. * @throws ClassCastException if the specified object cannot be compared
  125. * with the elements currently in this set
  126. * @throws NullPointerException if the specified element is null
  127. * and this set uses natural ordering, or its comparator
  128. * does not permit null elements
  129. */
  130. public boolean remove(Object o) {
  131. return m.remove(o)==PRESENT;
  132. }
  133. /**
  134. * Removes all of the elements from this set.
  135. * The set will be empty after this call returns.
  136. */
  137. public void clear() {
  138. m.clear();
  139. }
  140. /**
  141. * Adds all of the elements in the specified collection to this set.
  142. *
  143. * @param c collection containing elements to be added to this set
  144. * @return {@code true} if this set changed as a result of the call
  145. * @throws ClassCastException if the elements provided cannot be compared
  146. * with the elements currently in the set
  147. * @throws NullPointerException if the specified collection is null or
  148. * if any element is null and this set uses natural ordering, or
  149. * its comparator does not permit null elements
  150. */
  151. public boolean addAll(Collection<? extends E> c) {
  152. // Use linear-time version if applicable
  153. if (m.size()==0 && c.size() > 0 &&
  154. c instanceof SortedSet &&
  155. m instanceof TreeMap) {
  156. SortedSet<? extends E> set = (SortedSet<? extends E>) c;
  157. TreeMap<E,Object> map = (TreeMap<E, Object>) m;
  158. Comparator<?> cc = set.comparator();
  159. Comparator<? super E> mc = map.comparator();
  160. if (cc==mc || (cc != null && cc.equals(mc))) {
  161. map.addAllForTreeSet(set, PRESENT);
  162. return true;
  163. }
  164. }
  165. return super.addAll(c);
  166. }
  • ①向TreeSet中添加的数据,要求是同一个类的对象,不能添加不同类的对象。
  • ②两种排序方式:自然排序和定制排序
  • ③自然排序中,比较两个对象是否相同的标准:compareTo()返回0,不再是equals();
  1. public static void main(String[] args) {
  2. TreeSet<Object> treeSet = new TreeSet<>();
  3. treeSet.add(123);
  4. treeSet.add(456);
  5. treeSet.add(789);
  6. treeSet.add(456);
  7. System.out.println(treeSet);//[123, 456, 789]
  8. System.out.println("*****************************************");
  9. TreeSet<Object> set = new TreeSet<>();
  10. set.add(new User("Tom",22));
  11. set.add(new User("Jerry",24));
  12. set.add(new User("BeiBei",21));
  13. set.add(new User("DongDong",20));
  14. set.add(new User("MM",18));
  15. //set.add(new Integer(123));
  16. Iterator<Object> iterator = set.iterator();
  17. while (iterator.hasNext()){
  18. System.out.println(iterator.next());
  19. }
  20. }
  21. }
  22. class User implements Comparable{
  23. private String name;
  24. private int age;
  25. public User(String name, int age) {
  26. this.name = name;
  27. this.age = age;
  28. }
  29. public User() {
  30. }
  31. public String getName() {
  32. return name;
  33. }
  34. public void setName(String name) {
  35. this.name = name;
  36. }
  37. public int getAge() {
  38. return age;
  39. }
  40. public void setAge(int age) {
  41. this.age = age;
  42. }
  43. @Override
  44. public String toString() {
  45. return "User{" +
  46. "name='" + name + '\'' +
  47. ", age=" + age +
  48. '}';
  49. }
  50. @Override
  51. public int compareTo(Object o) {
  52. //姓名从大到小,年龄从小到大
  53. if (o instanceof User){
  54. User user= (User) o;
  55. int num= this.name.compareTo(user.name);
  56. if (num!=0){
  57. return -num;
  58. }else{
  59. return Integer.compare(this.age,user.age);
  60. }
  61. }else{
  62. throw new RuntimeException("类型不一致!");
  63. }
  64. }
  65. }

TreeSet定制排序

  • ①new一个Comparator对象,重写compare方法
  • ②将Comparator对象传入TreeSet的构造器
  • ③添加对象时就会按照compare方法进行比较
  1. public static void main(String[] args) {
  2. //照年龄从小到大排列
  3. Comparator comparator = new Comparator(){
  4. @Override
  5. public int compare(Object o1, Object o2) {
  6. if (o1 instanceof Dog&& o2 instanceof Dog){
  7. Dog d1= (Dog) o1;
  8. Dog d2= (Dog) o2;
  9. return Integer.compare(d1.getAge(),d2.getAge());
  10. }else{
  11. throw new RuntimeException("类型不一致!");
  12. }
  13. }
  14. };
  15. TreeSet<Object> set = new TreeSet<>(comparator);
  16. set.add(new Dog("Tom",22));
  17. set.add(new Dog("Jerry",22));
  18. set.add(new Dog("BeiBei",21));
  19. set.add(new Dog("DongDong",20));
  20. set.add(new Dog("MM",18));
  21. set.add(123);
  22. //set.add(new Integer(123));
  23. Iterator<Object> iterator = set.iterator();
  24. while (iterator.hasNext()){
  25. System.out.println(iterator.next());
  26. }
  27. }
  28. }
  29. class Dog{
  30. private String name;
  31. private int age;
  32. public Dog() {
  33. }
  34. public String getName() {
  35. return name;
  36. }
  37. public void setName(String name) {
  38. this.name = name;
  39. }
  40. public int getAge() {
  41. return age;
  42. }
  43. public void setAge(int age) {
  44. this.age = age;
  45. }
  46. public Dog(String name, int age) {
  47. this.name = name;
  48. this.age = age;
  49. }
  50. @Override
  51. public String toString() {
  52. return "Dog{" +
  53. "name='" + name + '\'' +
  54. ", age=" + age +
  55. '}';
  56. }
  57. }

2.map接口

map底层源码分析

  1. /**
  2. * Map:双列数据,用于存储具有键值对的数据,类似于函数的概念。
  3. * 1.HashMap:作为map的主要实现类,线程不安全的,效率高。可以存储null的key或value。
  4. *
  5. * *LinkedHashMap:HashMap的子类,保证在遍历map元素时,可以按照添加的顺序进行遍历。
  6. * 原因:在原有hashMap底层的基础结构上,添加了一对指针,指向前一个和后一个元素。
  7. *对于频繁的遍历操作,此类执行效率高于hashMap。
  8. *
  9. * 2.TreeMap:可以按照添加的键值对进行排序,实现便利排序。按照key来排序。
  10. *底层使用红黑树。
  11. *
  12. * 3.HashTable:古老的实现类。jdk1.0.,线程安全的,效率低,不可以存储null的key或value。
  13. *
  14. * *Properties:HashTable的子类。常用来处理配置文件。key和value都是String类型。
  15. *
  16. * HashMap的底层:jdk7 数组加链表
  17. * jdk8数组+链表+红黑树
  18. * 面试题:
  19. * 1.hashMap的底层实现原理:
  20. *
  21. * 2.HashMap和HashTable的异同:
  22. *
  23. * 二:Map中key-value的理解:
  24. * 1.key不可重复(无序),value可以重复。
  25. * 2.实际上放入map集合的是entry,entry有两个属性key和value。
  26. * 3.entry无序不可重复。
  27. * 4.key所在的类要重写hashcode()和equals()方法,针对于HashMap
  28. * 5.判断该元素存不存在,需要重写equals()。
  29. */

支持自然排序和定制排序

  1. public interface Map<K,V> {
  2. //里面定义了一个Entry接口
  3. interface Entry<K,V> {
  4. public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
  5. return (Comparator<Map.Entry<K, V>> & Serializable)
  6. (c1, c2) -> c1.getKey().compareTo(c2.getKey());
  7. }
  8. public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
  9. return (Comparator<Map.Entry<K, V>> & Serializable)
  10. (c1, c2) -> c1.getValue().compareTo(c2.getValue());
  11. }
  12. public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
  13. Objects.requireNonNull(cmp);
  14. return (Comparator<Map.Entry<K, V>> & Serializable)
  15. (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
  16. }
  17. public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
  18. Objects.requireNonNull(cmp);
  19. return (Comparator<Map.Entry<K, V>> & Serializable)
  20. (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
  21. }
  22. }

HashMap

底层源码分析

  1. /**
  2. * 以jdk7为例说明:
  3. * HashMap<Object, Object> map = new HashMap<>();//实例化以后,底层创建了长度为16的一维数组Entry[]table。
  4. * ....已经执行过多次put操作。。。。
  5. * map.put(1,666);//首先,计算key1的hash值,此hash值经过某种算法计算,得到在entry数组的存放位置。
  6. * 如果此位置的数据为空,此时的key1添加成功(成功一);如果此位置的数据不为空(意味着此位置存在一个或者多个数据),
  7. * 比较key1和已经存在的一个或多个数据的哈希值,如果key1的哈希值与已经存在的都不相同,此时添加成功(成功二)。
  8. * 如果如果key1的哈希值与已经存在的某个数据(key2-value2)的哈希值相同,继续比较,
  9. * 调用key1所在类的equals()方法,比较:
  10. * 如果equals()返回false:添加成功(成功三);如果返回true:使用value1替换value2.
  11. * 关于成功二和成功三:
  12. * 此时key1value1和原来的数据一链表的方式存储。
  13. * 在不断的添加过程中,涉及到扩容问题,当超出临界值,且要存放的位置非空时,默认的扩容方式,扩容为原来容量的2倍,并将原有的数据复制过来。
  14. * 在jdk8中的底层实现:
  15. * jdk8相比于底层实现方面的不同:
  16. * 1.new HashMap();底层没有创建一个长度为16的数组。
  17. * 2.jdk8底层是Node【】,不再是Entry【】。
  18. * 3.首次调用put方法时,底层创建长度为16的数组。
  19. * 4.原来jdk7底层结构只有数组加链表,jdk8又加入了红黑树,当数组某一个索引位置上的元素以链表形式存在的
  20. * 数据个数>8且当前数组长度>64时,此时此索引位置上的所有数据改为使用红黑树存储。
  21. */

HashMap基于Map接口实现,元素以键值对的方式存储,并且允许使用null 建和null 值, 因为key不允许重复,因此只能有一个键为null,另外HashMap不能保证放入元素的顺序,它是无序的,和放入的顺序并不能相同。HashMap是线程不安全的。

  1. public class HashMap<K,V> extends AbstractMap<K,V>
  2. implements Map<K,V>, Cloneable, Serializable {
  3. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始化大小 16
  4. static final float DEFAULT_LOAD_FACTOR = 0.75f; //负载因子0.75
  5. static final Entry<?,?>[] EMPTY_TABLE = {}; //初始化的默认数组
  6. transient int size; //HashMap中元素的数量
  7. int threshold; //判断是否需要调整HashMap的容量
  8. //当数组总长度>64,且单个节点的元素大于8个时,该节点的元素使用红黑树存储
  9. 当删除该节点元素时,当该节点的元素小于6个,从二叉树变为指针
  10. static final int TREEIFY_THRESHOLD = 8;
  11. static final int UNTREEIFY_THRESHOLD = 6;
  12. static final int MIN_TREEIFY_CAPACITY = 64;
  13. //底层使用指针
  14. static class Node<K,V> implements Map.Entry<K,V> {
  15. final int hash;
  16. final K key;
  17. V value;
  18. Node<K,V> next;
  19. Node(int hash, K key, V value, Node<K,V> next) {
  20. this.hash = hash;
  21. this.key = key;
  22. this.value = value;
  23. this.next = next;
  24. }
  25. //HashMap计算hash对key的hashcode进行了二次hash,以获得更好的散列值,然后对table数组长度取摸。
  26. int hash = hash(key.hashCode());
  27. int i = indexFor(hash, table.length);
  28. static int hash(int h) {
  29. // This function ensures that hashCodes that differ only by
  30. // constant multiples at each bit position have a bounded
  31. // number of collisions (approximately 8 at default load factor).
  32. h ^= (h >>> 20) ^ (h >>> 12);
  33. return h ^ (h >>> 7) ^ (h >>> 4);
  34. }
  35. static int indexFor(int h, int length) {
  36. return h & (length-1);
  37. //在该方法中,添加键值对时,首先进行table是否初始化的判断,如果没有进行初始化(分配空间,Entry[]数组的长度)。然后进行key是否为null的判断,如果key==null ,放置在Entry[]的0号位置。计算在Entry[]数组的存储位置,判断该位置上是否已有元素,如果已经有元素存在,则遍历该Entry[]数组位置上的单链表。判断key是否存在,如果key已经存在,则用新的value值,替换点旧的value值,并将旧的value值返回。如果key不存在于HashMap中,程序继续向下执行。将key-vlaue, 生成Entry实体,添加到HashMap中的Entry[]数组中。
  38. public V put(K key, V value) {
  39. if (table == EMPTY_TABLE) { //是否初始化
  40. inflateTable(threshold);
  41. }
  42. if (key == null) //放置在0号位置
  43. return putForNullKey(value);
  44. int hash = hash(key); //计算hash值
  45. int i = indexFor(hash, table.length); //计算在Entry[]中的存储位置
  46. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  47. Object k;
  48. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  49. V oldValue = e.value;
  50. e.value = value;
  51. e.recordAccess(this);
  52. return oldValue;
  53. }
  54. }
  55. modCount++;
  56. addEntry(hash, key, value, i); //添加到Map中
  57. return null;
  58. }
  59. 添加到方法的具体操作,在添加之前先进行容量的判断,如果当前容量达到了阈值,并且需要存储到Entry[]数组中,先进性扩容操作,空充的容量为table长度的2倍。重新计算hash值,和数组存储的位置,扩容后的链表顺序与扩容前的链表顺序相反。然后将新添加的Entry实体存放到当前Entry[]位置链表的头部。在1.8之前,新插入的元素都是放在了链表的头部位置,但是这种操作在高并发的环境下容易导致死锁,所以1.8之后,新插入的元素都放在了链表的尾部。
  60. /*
  61. * hash hash值
  62. * key 键值
  63. * value value值
  64. * bucketIndex Entry[]数组中的存储索引
  65. * /
  66. void addEntry(int hash, K key, V value, int bucketIndex) {
  67. if ((size >= threshold) && (null != table[bucketIndex])) {
  68. resize(2 * table.length); //扩容操作,将数据元素重新计算位置后放入newTable中,链表的顺序与之前的顺序相反
  69. hash = (null != key) ? hash(key) : 0;
  70. bucketIndex = indexFor(hash, table.length);
  71. }
  72. createEntry(hash, key, value, bucketIndex);
  73. }
  74. void createEntry(int hash, K key, V value, int bucketIndex) {
  75. Entry<K,V> e = table[bucketIndex];
  76. table[bucketIndex] = new Entry<>(hash, key, value, e);
  77. size++;
  78. }
  79. HashMap里面实现一个静态内部类Entry,其重要的属性有 hash,key,value,next。
  80. HashMap里面用到链式数据结构的一个概念。上面我们提到过Entry类里面有一个next属性,作用是指向下一个Entry。打个比方, 第一个键值对A进来,通过计算其key的hash得到的index=0,记做:Entry[0] = A。一会后又进来一个键值对B,通过计算其index也等于0,现在怎么办?HashMap会这样做:B.next = A,Entry[0] = B,如果又进来C,index也等于0,那么C.next = B,Entry[0] = C;这样index=0的地方其实存取了A,B,C三个键值对,他们通过next这个属性链接在一起。也就是说数组中存储的是最后插入的元素。
  81. void addEntry(int hash, K key, V value, int bucketIndex) {
  82. Entry<K,V> e = table[bucketIndex];
  83. table[bucketIndex] = new Entry<K,V>(hash, key, value, e); //参数e, 是Entry.next
  84. //如果size超过threshold,则扩充table大小。再散列
  85. if (size++ >= threshold)
  86. resize(2 * table.length);
  87. }
  88. //添加方法精讲
  89. public V put(K key, V value) {
  90. //调用putVal()方法完成
  91. return putVal(hash(key), key, value, false, true);
  92. }
  93. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  94. boolean evict) {
  95. Node<K,V>[] tab; Node<K,V> p; int n, i;
  96. //判断table是否初始化,否则初始化操作
  97. if ((tab = table) == null || (n = tab.length) == 0)
  98. n = (tab = resize()).length;
  99. //计算存储的索引位置,如果没有元素,直接赋值
  100. if ((p = tab[i = (n - 1) & hash]) == null)
  101. tab[i] = newNode(hash, key, value, null);
  102. else {
  103. Node<K,V> e; K k;
  104. //节点若已经存在,执行赋值操作
  105. if (p.hash == hash &&
  106. ((k = p.key) == key || (key != null && key.equals(k))))
  107. e = p;
  108. //判断链表是否是红黑树
  109. else if (p instanceof TreeNode)
  110. //红黑树对象操作
  111. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  112. else {
  113. //为链表,
  114. for (int binCount = 0; ; ++binCount) {
  115. if ((e = p.next) == null) {
  116. p.next = newNode(hash, key, value, null);
  117. //链表长度8,将链表转化为红黑树存储
  118. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  119. treeifyBin(tab, hash);
  120. break;
  121. }
  122. //key存在,直接覆盖
  123. if (e.hash == hash &&
  124. ((k = e.key) == key || (key != null && key.equals(k))))
  125. break;
  126. p = e;
  127. }
  128. }
  129. if (e != null) { // existing mapping for key
  130. V oldValue = e.value;
  131. if (!onlyIfAbsent || oldValue == null)
  132. e.value = value;
  133. afterNodeAccess(e);
  134. return oldValue;
  135. }
  136. }
  137. //记录修改次数
  138. ++modCount;
  139. //判断是否需要扩容
  140. if (++size > threshold)
  141. resize();
  142. //空操作
  143. afterNodeInsertion(evict);
  144. return null;
  145. }

LinkedHashMap

在LinkedHashMap中,是通过双联表的结构来维护节点的顺序的。每个节点都进行了双向的连接,维持插入的顺序(默认)。head指向第一个插入的节点,tail指向最后一个节点。

LinkedHashMap是HashMap的亲儿子,直接继承HashMap类。LinkedHashMap中的节点元素为Entry,直接继承HashMap.Node。

  1. 在HashMap类的put方法中,新建节点是使用的newNode方法。而在LinkedHashMap没有重写父类的put方法,而是重写了newNode方法来构建自己的节点对象。
  2. Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
  3. return new Node<>(hash, key, value, next);
  4. }
  5. Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
  6. LinkedHashMap.Entry<K,V> p =
  7. new LinkedHashMap.Entry<K,V>(hash, key, value, e);
  8. linkNodeLast(p);
  9. return p;
  10. }

LinkedHashMap相对于HashMap,增加了双链表的结果(即节点中增加了前后指针),其他处理逻辑与HashMap一致,同样也没有锁保护,多线程使用存在风险。

Map接口中定义的方法1

  1. public static void main(String[] args) {
  2. HashMap<Object, Object> map = new HashMap<>();
  3. map.put(1, 666);//添加
  4. map.putAll(map);//添加一个集合
  5. map.remove(1);//通过key移除
  6. map.clear();//移除集合中所元素
  7. map.size();//集合大小
  8. map.get(1);//通过key获取值
  9. map.containsKey(1);//判断是否包含指定key
  10. map.containsValue(666);//判断是否包含指定value
  11. map.isEmpty();//判断是否为空
  12. map.equals(map);//判断当前map和参数Object是否相等

Map中的常用方法二

  1. public static void main(String[] args) {
  2. HashMap<Object, Object> map = new HashMap<>();
  3. map.put(1,666);
  4. map.put(2,888);
  5. map.put(3,555);
  6. //遍历所的key:keySet
  7. Set<Object> set = map.keySet();
  8. Iterator<Object> iterator = set.iterator();
  9. while (iterator.hasNext()){
  10. System.out.println(iterator.next());
  11. }
  12. //遍历所的value:values
  13. Collection<Object> collection = map.values();
  14. Iterator<Object> iterator1 = collection.iterator();
  15. while (iterator1.hasNext()){
  16. System.out.println(iterator1.next());
  17. }
  18. //遍历所的key,value:entrySet
  19. Set<Map.Entry<Object, Object>> entries = map.entrySet();
  20. Iterator<Map.Entry<Object, Object>> iterator2 = entries.iterator();
  21. while (iterator2.hasNext()){
  22. System.out.println(iterator2.next());
  23. }
  24. }

HashTable

  1. public class Hashtable<K,V>
  2. extends Dictionary<K,V>
  3. implements Map<K,V>, Cloneable, java.io.Serializable {
  4. 属性:
  5. table:为一个Entry[]数组类型,Entry代表了“拉链”的节点,每一个Entry代表了一个键值对,哈希表的"key-value键值对"都是存储在Entry数组中的。
  6. count:HashTable的大小,注意这个大小并不是HashTable的容器大小,而是他所包含Entry键值对的数量。
  7. threshold:Hashtable的阈值,用于判断是否需要调整Hashtable的容量。threshold的值="容量*加载因子"。
  8. loadFactor:加载因子。
  9. modCount:用来实现“fail-fast”机制的(也就是快速失败)。所谓快速失败就是在并发集合中,其进行迭代操作时,若有其他线程对其进行结构性的修改,这时迭代器会立马感知到,并且立即抛出ConcurrentModificationException异常,而不是等到迭代完成之后才告诉你(你已经出错了)
  10. 构造方法:
  11. 1.默认构造函数,容量为11,加载因子为0.75:
  12. public Hashtable() {
  13. this(11, 0.75f);
  14. }
  15. 2.
  16. public Hashtable(int initialCapacity) {
  17. this(initialCapacity, 0.75f);
  18. }
  19. 3.
  20. public Hashtable(int initialCapacity, float loadFactor) {
  21. if (initialCapacity < 0)
  22. throw new IllegalArgumentException("Illegal Capacity: "+
  23. initialCapacity);
  24. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  25. throw new IllegalArgumentException("Illegal Load: "+loadFactor);
  26. if (initialCapacity==0)
  27. initialCapacity = 1;
  28. this.loadFactor = loadFactor;
  29. table = new Entry<?,?>[initialCapacity];
  30. threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
  31. }
  32. 重要方法
  33. public synchronized V get(Object key) {
  34. Entry<?,?> tab[] = table;
  35. int hash = key.hashCode();
  36. int index = (hash & 0x7FFFFFFF) % tab.length;
  37. for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
  38. if ((e.hash == hash) && e.key.equals(key)) {
  39. return (V)e.value;
  40. }
  41. }
  42. return null;
  43. }
  44. public synchronized V put(K key, V value) {
  45. // Make sure the value is not null
  46. if (value == null) {
  47. throw new NullPointerException();
  48. }
  49. // Makes sure the key is not already in the hashtable.
  50. Entry<?,?> tab[] = table;
  51. int hash = key.hashCode();
  52. int index = (hash & 0x7FFFFFFF) % tab.length;//计算出索引
  53. @SuppressWarnings("unchecked")
  54. //遍历该数组
  55. Entry<K,V> entry = (Entry<K,V>)tab[index];
  56. for(; entry != null ; entry = entry.next) {
  57. if ((entry.hash == hash) && entry.key.equals(key)) {
  58. V old = entry.value;
  59. entry.value = value;
  60. return old;
  61. }
  62. }
  63. addEntry(hash, key, value, index);
  64. return null;
  65. }
  66. private void addEntry(int hash, K key, V value, int index) {
  67. modCount++;
  68. Entry<?,?> tab[] = table;
  69. if (count >= threshold) {
  70. // Rehash the table if the threshold is exceeded
  71. rehash();
  72. tab = table;
  73. hash = key.hashCode();
  74. index = (hash & 0x7FFFFFFF) % tab.length;
  75. }
  76. // Creates the new entry.
  77. @SuppressWarnings("unchecked")
  78. Entry<K,V> e = (Entry<K,V>) tab[index];
  79. tab[index] = new Entry<>(hash, key, value, e);
  80. count++;
  81. }
  82. //扩容
  83. protected void rehash() {
  84. int oldCapacity = table.length;
  85. Entry<?,?>[] oldMap = table;
  86. // overflow-conscious code
  87. int newCapacity = (oldCapacity << 1) + 1;2倍+1
  88. if (newCapacity - MAX_ARRAY_SIZE > 0) {
  89. if (oldCapacity == MAX_ARRAY_SIZE)
  90. // Keep running with MAX_ARRAY_SIZE buckets
  91. return;
  92. newCapacity = MAX_ARRAY_SIZE;
  93. }
  94. Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
  95. modCount++;
  96. threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
  97. table = newMap;
  98. for (int i = oldCapacity ; i-- > 0 ;) {
  99. for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
  100. Entry<K,V> e = old;
  101. old = old.next;
  102. int index = (e.hash & 0x7FFFFFFF) % newCapacity;
  103. e.next = (Entry<K,V>)newMap[index];
  104. newMap[index] = e;
  105. }
  106. }
  107. }

TreeMap

  1. public class TreeMap<K,V>
  2. extends AbstractMap<K,V>
  3. implements NavigableMap<K,V>, Cloneable, java.io.Serializable
  4. {
  5. private final Comparator<? super K> comparator;
  6. private transient Entry<K,V> root;
  7. public Comparator<? super K> comparator() {
  8. return comparator;
  9. }

TreeMap两种添加方式的使用:

向treemap中添加数据,要求key必须是同一个类创建的对象,因为要按照类进行排序。

①自然排序

  1. public static void main(String[] args) {
  2. TreeMap<Object, Object> map = new TreeMap<>();
  3. map.put(new User("尹会东",23),"6666");
  4. map.put(new User("张贝贝",25),"6666");
  5. map.put(new User("刘淼",23),"6666");
  6. Set<Map.Entry<Object, Object>> set = map.entrySet();
  7. Iterator<Map.Entry<Object, Object>> iterator = set.iterator();
  8. while (iterator.hasNext()){
  9. System.out.println(iterator.next());
  10. }
  11. }
  12. }
  13. class User implements Comparable{
  14. private String name;
  15. private int age;
  16. public User(String name, int age) {
  17. this.name = name;
  18. this.age = age;
  19. }
  20. public User() {
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public int getAge() {
  29. return age;
  30. }
  31. public void setAge(int age) {
  32. this.age = age;
  33. }
  34. @Override
  35. public String toString() {
  36. return "User{" +
  37. "name='" + name + '\'' +
  38. ", age=" + age +
  39. '}';
  40. }
  41. @Override
  42. public int compareTo(Object o) {
  43. //姓名从大到小,年龄从小到大
  44. if (o instanceof User){
  45. User user= (User) o;
  46. int num= this.name.compareTo(user.name);
  47. if (num!=0){
  48. return -num;
  49. }else{
  50. return Integer.compare(this.age,user.age);
  51. }
  52. }else{
  53. throw new RuntimeException("类型不一致!");
  54. }
  55. }
  56. }

②定制排序

  1. public static void main(String[] args) {
  2. Comparator comparator = new Comparator() {
  3. @Override
  4. public int compare(Object o1, Object o2) {
  5. if (o1 instanceof Dog && o2 instanceof Dog){
  6. Dog d1= (Dog) o1;
  7. Dog d2= (Dog) o2;
  8. return Integer.compare(d1.getAge(),d2.getAge());
  9. }
  10. throw new RuntimeException("类型不一致!");
  11. }
  12. };
  13. TreeMap<Object, Object> map = new TreeMap<>(comparator);
  14. map.put(new Dog("尹会东",23),"6666");
  15. map.put(new Dog("张贝贝",25),"6666");
  16. map.put(new Dog("45646",56),"888");
  17. Set<Map.Entry<Object, Object>> set = map.entrySet();
  18. Iterator<Map.Entry<Object, Object>> iterator = set.iterator();
  19. while (iterator.hasNext()){
  20. System.out.println(iterator.next());
  21. }
  22. }
  23. }
  24. class Dog{
  25. private String name;
  26. private int age;
  27. public Dog() {
  28. }
  29. public String getName() {
  30. return name;
  31. }
  32. public void setName(String name) {
  33. this.name = name;
  34. }
  35. public int getAge() {
  36. return age;
  37. }
  38. public void setAge(int age) {
  39. this.age = age;
  40. }
  41. public Dog(String name, int age) {
  42. this.name = name;
  43. this.age = age;
  44. }
  45. @Override
  46. public String toString() {
  47. return "Dog{" +
  48. "name='" + name + '\'' +
  49. ", age=" + age +
  50. '}';
  51. }
  52. }

Properties

  1. public synchronized Object setProperty(String key, String value) {
  2. return put(key, value);
  3. }
  4. public synchronized void load(Reader reader) throws IOException {
  5. load0(new LineReader(reader));
  6. }
  7. private void load0 (LineReader lr) throws IOException {
  8. char[] convtBuf = new char[1024];
  9. int limit;
  10. int keyLen;
  11. int valueStart;
  12. char c;
  13. boolean hasSep;
  14. boolean precedingBackslash;
  15. while ((limit = lr.readLine()) >= 0) {
  16. c = 0;
  17. keyLen = 0;
  18. valueStart = limit;
  19. hasSep = false;
  20. //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
  21. precedingBackslash = false;
  22. while (keyLen < limit) {
  23. c = lr.lineBuf[keyLen];
  24. //need check if escaped.
  25. if ((c == '=' || c == ':') && !precedingBackslash) {
  26. valueStart = keyLen + 1;
  27. hasSep = true;
  28. break;
  29. } else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) {
  30. valueStart = keyLen + 1;
  31. break;
  32. }
  33. if (c == '\\') {
  34. precedingBackslash = !precedingBackslash;
  35. } else {
  36. precedingBackslash = false;
  37. }
  38. keyLen++;
  39. }
  40. while (valueStart < limit) {
  41. c = lr.lineBuf[valueStart];
  42. if (c != ' ' && c != '\t' && c != '\f') {
  43. if (!hasSep && (c == '=' || c == ':')) {
  44. hasSep = true;
  45. } else {
  46. break;
  47. }
  48. }
  49. valueStart++;
  50. }
  51. String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
  52. String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
  53. put(key, value);
  54. }
  55. }

Properties处理配置文件

  1. public static void main(String[] args) {
  2. Properties prop=new Properties();
  3. FileInputStream fileInputStream=null;
  4. try {
  5. fileInputStream = new FileInputStream("jdbc.properties");
  6. prop.load(fileInputStream);
  7. String name=prop.getProperty("user");
  8. System.out.println(name);
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. }finally {
  12. try {
  13. if (fileInputStream!=null){
  14. fileInputStream.close();
  15. }
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }

3.collections工具类

Collections工具类:操作set,map,list的工具类

面试题:Collection和Collections的区别:

  1. public static void main(String[] args) {
  2. //排序
  3. ArrayList<Object> list = new ArrayList<>();
  4. list.add(new Integer(1));
  5. list.add(new Integer(2));
  6. list.add(new Integer(3));
  7. Collections.reverse(list);//反转list本身
  8. Collections.shuffle(list);//随机化处理
  9. // Collections.sort(list);//升序排序
  10. Collections.swap(list,1,2);//交换两处位置的元素
  11. Collections.frequency(list,1);//指定元素出现的次数
  12. //同步控制
  13. List<Object> list1 = Collections.synchronizedList(list);//返回的list1就是线程安全的list
  14. }

十,泛型

jdk1.5新特性泛型
把元素的类型设计成一个参数,这个参数类型叫做泛型。
为什么要使用泛型?
1.类型无限制,类型不安全。
2.类型强制转换时,容易出现异常。
ClassCastException

  1. 集合中使用泛型
  2. 集合接口或类在jdk5.0都修改为带泛型的结构。
  3. 在实例化集合类时,可以指明泛型的类型。
  4. 指明完以后,在集合类或接口中,凡是定义接口或类时,内部结构使用到类的泛型位置,都指定为实例化的泛型。
  5. 泛型的类型必须是一个类。,使用基本数据类型时,需要转换为包装类。
  6. 如果实例化时未指明泛型,默认为Object类型。
  1. public static void main(String[] args) {
  2. ArrayList<Integer> list = new ArrayList<>();
  3. list.add(99);
  4. list.add(100);
  5. list.add(88);
  6. for (Integer integer:list){
  7. System.out.print(integer+" ");
  8. }
  9. System.out.println();
  10. System.out.println("-------------------------------------------------------");
  11. Iterator<Integer> iterator = list.iterator();
  12. while (iterator.hasNext()){
  13. System.out.print(iterator.next()+" ");
  14. }
  15. System.out.println("-------------------------------------------------------");
  16. HashMap<String, Integer> map = new HashMap<>();
  17. map.put("第一个",123);
  18. map.put("第二个",456);
  19. map.put("第个",789);
  20. Set<Map.Entry<String, Integer>> set = map.entrySet();
  21. Iterator<Map.Entry<String, Integer>> iterator1 = set.iterator();
  22. while (iterator1.hasNext()){
  23. System.out.print(iterator1.next()+" ");
  24. }
  25. System.out.println("-------------------------------------------------------------");
  26. }

自定义泛型结构:泛型类,接口,方法

  1. /**
  2. * 泛型类被某个类继承:
  3. * ①public class SubOrder extends Order<Integer>//此时子类时普通类
  4. * 由于子类在继承带泛型的父类时,指明了泛型类型,则实例化子类对象时,不再需要指明泛型。
  5. * ②public class SubOrder1<T> extends Order<T>//此时子类也是泛型类
  6. *
  7. * 自定义泛型的注意点
  8. * ①泛型不同的引用不能相互赋值
  9. * ArrayList<Integer>list1=null;
  10. * ArrayList<String>list2=null;
  11. * 此时list1和list2不能相互赋值。
  12. * ②类型推断
  13. * Order<String> order1 = new Order<>();
  14. * ③静态方法中不能使用类的泛型
  15. *
  16. * 泛型方法:在方法中出现了泛型的结构,泛型参数与类的泛型参数没有任何关系。
  17. * 换句话说,泛型方法所属的类是不是泛型类都没有关系。
  18. * 泛型方法可以声明为静态的。原因:泛型参数是在调用方法时确定的。并非在实例化类时确定。
  19. */
  1. /**
  2. * @author yinhuidong
  3. * @createTime 2020-04-10-15:23
  4. * 案例需求:
  5. * 一个学生类包含两个属性:String类型的name和不确定类型的score
  6. * 老师一登记成绩:优秀,良好,及格
  7. * 老师二登记成绩:89.5,100.。。。
  8. * 老师三登记成绩:A,B,C,
  9. * 需求二:
  10. * 一个指定类型的学生类
  11. */
  12. public class Test1 {
  13. @Test
  14. public void test1() {
  15. //实例化子类对象时,指明带泛型的类型
  16. //泛型不指定就相当于默认Object类型
  17. //如果泛型结构是借口或抽象类,不可以实例化对象
  18. //静态方法中不能使用类的泛型,原因:类的泛型是在对象实例化时指定的,而静态方法是在类加载时加载的
  19. //异常类不能声明为泛型类
  20. //jdk1.8类型推断
  21. Student<String> student = new Student<>("张三", "优秀");
  22. Student<Double> student1 = new Student<>("李四", 90.5);
  23. Student<Character> student2 = new Student<>("王五", 'A');
  24. }
  25. @Test
  26. public void test2() {
  27. //由于子类在继承带泛型的父类时,指明了带泛型的类型,则实例化子类对象时,不再需要指明泛型。
  28. Student2 student = new Student2("zhangsan", "优秀");
  29. }
  30. @Test
  31. public void test3(){
  32. Integer[] arr = new Integer[4];
  33. arr[0]=1;
  34. arr[1]=2;
  35. arr[2]=3;
  36. arr[3]=4;
  37. Student2 student = new Student2();
  38. //泛型方法在调用时指明泛型参数的类型
  39. List<Integer> list = student.copy(arr);
  40. for (Integer i:list){
  41. System.out.println(i);
  42. }
  43. }
  44. }
  45. class Student<T> {
  46. private String name;
  47. private T score;
  48. public Student() {
  49. }
  50. public Student(String name, T score) {
  51. this.name = name;
  52. this.score = score;
  53. }
  54. public String getName() {
  55. return name;
  56. }
  57. public void setName(String name) {
  58. this.name = name;
  59. }
  60. public T getScore() {
  61. return score;
  62. }
  63. public void setScore(T score) {
  64. this.score = score;
  65. }
  66. @Override
  67. public String toString() {
  68. return "Student{" +
  69. "name='" + name + '\'' +
  70. ", score=" + score +
  71. '}';
  72. }
  73. }
  74. class Student2 extends Student<String> {
  75. public Student2() {
  76. }
  77. public Student2(String name, String score) {
  78. super(name, score);
  79. }
  80. /**
  81. * 泛型方法:
  82. * 在方法中出现了泛型结构,泛型参数与类的泛型参数没有任何关系
  83. * 泛型方法可以声明为static,原因:泛型参数是在调用方法时确定的,而不是在实例化类时确定的
  84. */
  85. public <E> List<E> copy(E[] arr) {
  86. ArrayList<E> list = new ArrayList<>();
  87. for (E e : arr) {
  88. list.add(e);
  89. }
  90. return list;
  91. }
  92. }

通配符的使用

类A是类B的父类,G和G是没有关系的,二者共有的父类是G<?>。

  1. /**
  2. * @author yinhuidong
  3. * @createTime 2020-04-10-15:57
  4. * 1.泛型在继承方面的提现
  5. *
  6. * 2.通配符的使用
  7. */
  8. public class Test2 {
  9. /**
  10. * 泛型在继承方面的提现
  11. * 类A是类B的父类,
  12. * G<A>和G<B>不具有子父类关系
  13. * 二者是并列关系,二者公共的父类时G<?>
  14. *
  15. * 类A是类B的父类,A<G>是B<G>的子父类
  16. */
  17. @Test
  18. public void test1(){
  19. List<Object> list1=null;
  20. List<Integer> list2=null;
  21. //此时的list1和list2类型不具有子父类关系
  22. //list1=list2;
  23. }
  24. /**
  25. * 通配符的使用
  26. * ?
  27. * 有限制条件的通配符的使用
  28. * <? extends Person> ?代表的类型必须是Person的子类
  29. * <? implement PersonDao> ?代表的类型必须实现了PersonDao接口
  30. * <? super Person> ?代表的类型必须是Person或Person的父类
  31. */
  32. public void show(List<?> list){
  33. //list.add(1);
  34. //此时list<?>并不能再添加数据(null除外)
  35. list.add(null);
  36. Iterator<?> iterator = list.iterator();
  37. while (iterator.hasNext()){
  38. System.out.println(iterator.next());
  39. }
  40. //读取数据:允许,返回类型为Object类型
  41. Object o = list.get(0);
  42. }
  43. @Test
  44. public void test2(){
  45. ArrayList<Integer> list = new ArrayList<>();
  46. list.add(1);
  47. list.add(2);
  48. list.add(3);
  49. show(list);
  50. }
  51. }