2023年之我拿起“java“ java基础进阶1

文章目录

java基础进阶

继承 e x t e n d s \color{red}{继承extends} 继承extends

  所有类直接或间接地继承Object类。

//创建一个类Father继承Object类
class Father extends Object{
    int age = 30;
    int num = 1;
    public void show(){
        System.out.println("这是父类");
    }
}

//创建一个类son继承Father类
class Son extends Father{
    int age = 10;
    public void show(){
        int age = 5;
        //父类地私有成员无法访问
        System.out.println(num);
        //打印结果 1
        //解释:num只存在于父类中,值为1
        System.out.println("局部"+age);
        //打印结果 局部5
        //解释:在show方法中存在 age 所以优先读取show方法的age=5值
        System.out.println("本对象"+ this.age);
        //打印结果 本对象10
        //解释:这里使用了this关键字,所以打印成员变量 age=10
        System.out.println("father"+super.age);
        //打印结果 father30
        //解释:这里使用了super关键字,所以打印父类中 age=30
        System.out.println("这是子类");
    }
    public void method(){
        super.show();
        //打印结果 这是父类
        //使用super关键字 调用父类中的方法
    }
}

public class test {
	//函数入口 
    public static void main(String[] args) {
        //创建对象
        Son son = new Son();
        son.show();
        son.method();
    }
}

抽象类 a b s t r a c t \color{red}{抽象类abstract} 抽象类abstract

  1.抽象方法和抽象类必需使用abstract关键字修饰。
  2.抽象类不能实例化(不能创建对象)。
  3.抽象类中可以有抽象方法也可以有非抽象方法,但是抽象方法必修在抽象类中。

抽象方法:一种规范,强制子类必须要这种方法。
非抽象方法:提高代码的复用性,让子类直接继承使用。

  4.抽象类的子类,要么重写抽象类中所有的抽象方法,要么子类是一个抽想类。

//写一个抽象方法Animal
//抽象方法和抽象类必需使用abstract关键字修饰
abstract class Animal{
    //一个方法要么有方法体,要么此方法是一个抽象方法
    public abstract void eat();

    public void show(){

    }
}

//写一个Dog方法继承Animal
class Dog extends Animal{

    //抽象类的子类,要么重写抽象类中所有的抽象方法,要么子类是一个抽想类
    @Override
    public void eat() {

    }
}

public class test1 {
    public static void main(String[] args) {
        //创建对象
        Dog dog = new Dog();
        //调用eat()
        dog.eat();
    }
}

s t a t i c 修饰静态成员 \color{red}{static修饰静态成员} static修饰静态成员

静态成员

特点

  1.静态成员可以被本类中所有对象共享。
  2.静态成员可以通过类名调用也可以通过对象调用,但是推荐使用类名调用!
  3.静态成员随着类的加载而加载,优先于对象存在。

注意事项

  1.非静态方法可以访问任何成员。
  2.静态方法中只能访问静态成员,要想访问非静态成员需要使用对象调用。

静态成员具体使用方法

Student.java
public class Student {
    public String name;
    public int age;
    //被static修饰的成员
    public static String school;

    public void show(){
        System.out.println(name+" "+age+" "+school);
    }
}
Staticdemo.java
public class StaticDemo {
    public static void main(String[] args) {
        //可以直接给school赋值
        Student.school = "清华";
        //创建一个Student()对象 为s1
        Student s1 = new Student();
        s1.name="张三";
        s1.age=18;
        s1.show();
        //打印结果 张三 18 清华

        System.out.println("===================");
        //创建一个Student()对象 为s2
        Student s2 = new Student();
        s2.name="刘三";
        s2.age=18;
        s2.show();
        //打印结果 刘三 18 清华
    }
}

  虽然我们在创建对象后,没有给school赋值,但是我们,在开始已经赋值过了,并且school已经被static修饰。
  在这里我们new了两个对象,但是我们在第二个new的对象s2中没有输入学校,school应该为null ,但是很显然打印的结果中有数据,那是因为static修饰了school

接口实现 \color{red}{接口实现} 接口实现

接口

  1.接口关键字 interface。
  2.接口不能实例化。
  3.类与接口之间的关系是实现关系,通过implements 关键字实现

public class 类名 implements 接口名{}

  4.接口的子类(实现类)

要么重写接口中所有方法。
要么是抽象类。

public interface Inter{
    public abstract void show();
    public abstract void method();
}

interface Inter2{
    public abstract void show2();
}

//实现类InterImpl 
//InterImpl类先继承了Object类 然后实现了Inter,Inter2接口
class InterImpl extends  Object implements Inter ,Inter2{

    //要重写抽象类
    @Override
    public void show() {
        
    }

    @Override
    public void method() {

    }

    @Override
    public void show2() {

    }
}

接口中的成员组成

  1.成员变量:都是常量,默认修饰符public static final
  2.构造方法:没有。
  3.成员方法:

JDK8版本前:都是抽象方法 默认修饰符 public abstract
JDk8版本:增加了 默认方法和静态方法。
JDK9版本:增加了 私有方法。

public class test3 {
    public static void main(String[] args) {
        //调用num
        int result = InterA.num;
        System.out.println(result);
        //打印结果 10
    }
}

interface InterA{
	//成员变量num
    public static final int num = 10;
    public abstract void show();
}
默认方法

   允许在接口中定义非抽象方法,但是需要使用关键字default修饰,这就是默认方法。
  作用:解决接口的省级问题。
  格式:

public default 返回值类型 方法名 (参数){……}
public default void show(){……}

  注意事项:
  1.默认方法不是抽象方法,所以不强制被重写,但是可以被重写,重写的时候要去掉default关键字。
  2.public 可以省略,default不能省略。
  3.如果实现了多个接口,多个接口中存在相同方法声明,子类就必须对该方法进行重写。

public class test4 {
    public static void main(String[] args) {

    }
}
//创建接口 Inter1
interface Inter1{
    public abstract void show();

    public default void method(){
        System.out.println("Inter1中的默认接口方法");
    }
}

//创建接口 InterB
interface InterB{
    public abstract void show();

    public default void method(){
        System.out.println("InterB中的默认接口");
    }
}

class InterImpl1 implements Inter1{

    //抽象方法需要重写
    @Override
    public void show() {

    }

    //默认方法可以重写,也可以不重写
    //重写格式如下
    @Override
    public void method() {
        Inter1.super.method();
    }
}

class InterImpl2 implements Inter1,InterB{

    //重写抽象方法
    @Override
    public void show() {
        
    }

    //此处的默认方法必须重写
    //实现的接口Inter1,InterB中有相同的method方法,必须重写
    @Override
    public void method() {
        InterB.super.method();
    }
}
静态方法

  1.格式:public static 返回值类型 方法名(参数){}
  2.作用:方便使用。
  3.注意事项:

1.public 可以省略,但是static不可以省略。
2.调用方式只有一种,可以通过接口名字进行调用。

public class test5 {
    public static void main(String[] args) {
        InterAA.showAA();
        //打印结果是 接口的方法是静态的……
    }
}

interface InterAA{
    //接口中含有静态方法
    public static void showAA(){
        System.out.println("接口的方法是静态的……");
    }
}
class InterImplAA implements InterAA{

}
私有接口(保证自己的jdk版本要大于等于9版本)

方法1

interface Inter{

    public static void start(){
        System.out.println("start方法执行...");
        log();
    }

    public static  void end(){
        System.out.println("end方法执行...");
        log();
    }

    private static  void log(){
        System.out.println("日志记录");
    }

}

方法2

interface Inter1{

    public default void start(){
        System.out.println("start方法执行...");
        log();
    }

    public default   void end(){
        System.out.println("end方法执行...");
        log();
    }

    private  void log(){
        System.out.println("日志记录");
    }

}

类和接口的关系

类和类的关系

  继承关系,只能是继承,但是可以多层继承。

类和接口的关系

  实现关系,可以单实现,也可以多实现,还可以在继承一个类的同时实现多个接口。

接口和接口的关系

  继承关系,可以多继承,也可以单继承。

抽象类与接口之间的区别

相同点

  1.抽象类与接口都作为父类,但是都不可以创建对象。

不同点

  1成员的区别
成员变量:
抽象类:可以是常量,也可以是变量。
接口:只能是常量,默认修饰符 public stasic final
成员方法:
抽象类:可以是抽象方法,也可以是非抽象方法。
接口:JDK8之前:只能是抽象方法,默认修饰符 public abstract
      JDK8版本:增加了默认方法和静态方法。
      JDK9版本:增加了私有方法。
构造方法:
抽象类:有。
接口:没有。

设计理念

  抽象类可以存放事物的共性内容。
  接口可以存放事物的规则和事物的扩展。

f i n a l \color{red}{final} final

final能修饰什么

  1.final 可以修饰类:是一个最终类,不能被继承,没有子类(太监类)。
  2.final 可以修饰变量:是一个常量(自定义常量),只能被赋值一次。
自定义常量每个单词都需要大写,多个单词用下划线。
  3.final 可以修饰方法:是一个最终的方法,不能被重写。
  4.final 修饰引用数据类型,final修饰的应用类型内容可以修改,地址不允许修改。

枚举 \color{red}{枚举} 枚举

sex.java

//枚举性别
public enum sex {
    //男,女,保密
    BOY(),GIRL(),MI();
}

EnumDemo.java

public class EnumDemo {
    public static void main(String[] args) {
        //接受枚举
        Enum result = sex.BOY;
        System.out.println(result);
        //打印的结果 BOY
    }
}

消化一下知识在接着往下看吧!!! \color{red}{消化一下知识在接着往下看吧!!!} 消化一下知识在接着往下看吧!!!

多态 \color{red}{多态} 多态

多态前提

  1.需要有继承/实现的关系。
  2.方法重写.
  3父类的引用指向了子类的对象/接口的引用指向了实现类的对象。

多态成员的访问

  1.成员变量:编译看左边(父类),执行看左边(父类)。
  2.成员方法:编译看左边(父类),执行看右边(子类),如果右边没有,会继承父类。
  3.构造方法:和继承一样,每个构造方法默认第一行都会有super() 去访问父类的无参构造。

public class test {
    public static void main(String[] args) {
        //多态
        //父类的引用指向子类
        Animal animal = new Dog();
        
        animal.eat();
        //打印结果 狗吃肉

        //成员变量:编译看左边(父类),执行看左边(父类)
        System.out.println(animal.a);
        //打印结果 10
        
        //成员方法:编译看左边(父类),执行看右边(子类)
        animal.show();
        //打印结果 子类的show方法!
        
        //成员方法:编译看左边(父类),执行看右边(子类),如果右边没有,会继承父类
        animal.show2();
        //不打印 在父类中有show2,但是子类中没有,继承父类
    }
}

//创建一个动物抽象类
abstract class Animal{
    int a = 10;
    public abstract void eat();
    
    public void show(){
        System.out.println("父类的show方法!");
    }
    
    public void show2(){
        
    }
}

//创建一个Dog类继承Animal类
class Dog extends Animal{

    int a = 20;
    
    //抽象方法必须重写
    @Override
    public void eat() {
        System.out.println("狗吃肉");
    }
    
    public void show(){
        System.out.println("子类的show方法!");
    }
}

多态的有缺点

  优点:提高代码的扩展性。

  缺点:不能访问子类的特有功能。

instanceof

  格式:对象名 instanceof 应用数据类型。

Animal1.java
//创建一个抽象类 Animal1
public abstract class Animal1 {
    public abstract void eat();
}

//创建一个Dog1类继承Animal1类
class Dog1 extends Animal1{

    //重写抽象方法
    @Override
    public void eat() {
        System.out.println("狗吃肉");
    }
    //狗的特有功能,看家
    public void lookHome(){
        System.out.println("狗看家");
    }
}

//创建一个Cat1类继承Animal1类
class Cat1 extends Animal1{

    //重写抽象方法
    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }

    //猫的特有功能,捉老鼠
    public void CatchMouse(){
        System.out.println("猫捉老鼠");
    }
}

//创建一个Pig1类继承Animal1类
class Pig1 extends Animal1{

    //重写抽象方法
    @Override
    public void eat() {
        System.out.println("猪吃白菜");
    }

    //猪的特有功能,能睡
    public  void sleep(){
        System.out.println("猪特能睡");
    }
}

test2.java
/*
多态的转型:
        向上转型:把子类型的对象赋值给了父类类型变量
            Animal a =new Dog()
        向下转型:把父类类型的数据赋值给了子类类型的变量
            Dog dog = (Dog)a;
        注意:向下转换的类型和目标类型不一致会发生ClassCastException(类型转换异常)
*/
public class test2 {
    public static void main(String[] args) {
        useAnimal1(new Dog1());
        useAnimal1(new Cat1());
        useAnimal1(new Pig1());
    }

    public static void useAnimal1(Animal1 animal1){
        animal1.eat();

        if(animal1 instanceof Dog1){
            Dog1 dog1 = (Dog1) animal1;
            dog1.lookHome();
        }

        if(animal1 instanceof Cat1){
            Cat1 cat1 = (Cat1) animal1;
            cat1.CatchMouse();
        }

        if(animal1 instanceof Pig1){
            Pig1 pig1 = (Pig1) animal1;
            pig1.sleep();
        }
    }
}

内部类 \color{red}{内部类} 内部类

什么是内部类

  1.一个类A内部定义一个内部类B,那么B就是A的内部类,A可以称为外部类。

成员内部类如何实例化对象

  1.外部类.内部类 对象名 = new 外部类构造方法().new 内部类构造方法();

成员内部类方法中局部变量,成员变量,外部类成员变量名字相同,如何访问

  1.局部变量:直接访问。
  2.内部类成员变量:this 访问
  3.外部类成员变量:外部类名. this 访问

public class test {
    public static void main(String[] args) {
        //内部类实例化
        Person.Heart heart = new Person().new Heart();

        heart.brats();
        //打印结果 咚咚咚~~
        heart.show();
        //打印结果 30 20 10

        //外部类实例化
        Person person = new Person();
        person.show();
        //不打印
    }
}

//外部类
class Person{
    private int age = 10;

    public void show(){

    }

    //内部类
    class Heart{
        private int age = 20;
        private int rate = 80;

        public void brats(){
            System.out.println("咚咚咚~~");
        }

        public void show(){
            int age = 30;
            System.out.println(age);
            //打印结果 30
            System.out.println(this.age);
            //打印结果 20
            System.out.println(Person.this.age);
            //打印结果 10
        }
    }
}

匿名内部类

  1.匿名内部类是一个特殊的内部类,从命名可以看出,匿名内部类是没有类名,因此这个内部类只能用一次。
  2.有什么场景可以使用呢?匿名内部类一般用来简化代码,当要快速实现一个抽象类或者接口的抽象方法,我们就可以使用匿名内部类来简化,可以不用专门定义一个有名的内部类来操作。
  3.要使用匿名内部类,必须要有一个父类或者接口。

  格式:

new 抽象类/接口名(){
	需要重写抽象类或者接口中的抽象方法
}
public class test {
    public static void main(String[] args) {
        //第一种方法 传入实现类
        useSwimming(new SwimmingImpl());

        //第二种方法 匿名内部类
        useSwimming(new Swimming() {
            @Override
            public void swim() {
                System.out.println("游泳");
            }
        });
        
        //第三种方法
        useSwimming(new SwimmingImpl(){
            @Override
            public void swim() {
                System.out.println("游泳");
            }
        });
    }

    public static void useSwimming(Swimming swimming ){
        swimming.swim();
    }
}

//创建一个接口
interface Swimming{
    public abstract void swim();
}

class SwimmingImpl implements Swimming{

    //重写抽象方法
    @Override
    public void swim() {
        System.out.println("我们去游泳");
    }
}

匿名内部类的使用

  1.使用父类型变量多态接受该匿名子类对象。
  2.以匿名对象的方式调用。
直接调用的方式使用。
当做方法的参数传递。
当做方法的返回值使用。

public class test {
    public static void main(String[] args) {
        //1.使用父类型变量多态接受该匿名子类对象
        Flyable flyable = new Flyable() {
            @Override
            public void fly() {
                System.out.println("飞");
            }
        };
        flyable.fly();

        //2.以匿名对象的方式调用

        //(1)直接调用的方法使用
        new Flyable(){

            @Override
            public void fly() {
                System.out.println("飞2");
            }
        }.fly();

        // (2)当作方法参数传递
        useFlyable(new Flyable() {
            @Override
            public void fly() {
                System.out.println("飞3");
            }
        });
    }

    public static void useFlyable(Flyable flyable){
        flyable.fly();
    }

    // (3)当作方法的返回值调用
    public static Flyable getFlyable(){
        return new Flyable() {
            @Override
            public void fly() {
                System.out.println("飞4");
            }
        };
    }
}

//创建一个接口
interface Flyable{
    public abstract void fly();
}

日期类 \color{red}{日期类} 日期类

Date类

获取当前时间
Date date = new Date();
System.out.println(date);
//打印的是当前时间 格式如下
//Tue Aug 29 19:25:29 CST 2023
东八区时间

1970/1/1 0:0:0 + date毫秒值

//1000L 是1秒 这里需要放入 long类型的数据
Date date = new Date(1000L);
System.out.println(date);
//打印的是东八区时间 格式如下
//Thu Jan 01 08:00:01 CST 1970
getTime()

获取当前时间到东八区时间之间的毫秒值

Date date = new Date();
System.out.println(date.getTime());
//返回值类型 long类型的毫秒值 = 当前Date代表的时间 - 1970/1/1 0:0:0
//打印结果 1693308651416
setTime()

Date对象 = 1970/1/1 0:0:0 + time毫秒值

Date date = new Date();
date.setTime(1000L);
// Date对象 = 1970/1/1 0:0:0 + time毫秒值
System.out.println(date);
//打印结果 Thu Jan 01 08:00:01 CST 1970

类型转换

Date类型转化为String类型
Date date = new Date();
//创建的是日期格式化对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(date);
System.out.println(strDate);
//打印结果 2023-08-30 11:20:31
String类型转Date类型
public class test {
    public static void main(String[] args) throws ParseException {
        String s = "2023-08-30 11:20:31";
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(s);
        //这里会出现异常,我们按住 Alt + Enter 将异常抛出去
        System.out.println(date);
        //打印结果 Wed Aug 30 11:20:31 CST 2023
    }
}

小案例

计算自己活了多少年
public class test {
    public static void main(String[] args) throws ParseException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入自己的生日(xxxx-xx-xx)");
        String birthday = sc.nextLine();
        //输入 2000-01-01

        //将字符串转化为日期类
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse(birthday);

        //拿到从生日到1970/1/1所经历的毫秒值
        long start = d1.getTime();

        //获取当前时间
        Date d2 = new Date();

        //拿到从当前时间到1970/1/1所经历的毫秒值
        long end = d2.getTime();

        long result = (end-start)/(1000L*60*60*24);
        System.out.println("你活了"+result+"天");
        //打印结果 你活了8642天
    }
}

LocalDateTime类

获取当前系统时间
public class test {
    public static void main(String[] args){
        LocalDateTime time = LocalDateTime.now();
        System.out.println(time);
        //打印结果 2023-08-30T11:49:21.390632800
    }
}
使用指定年月日和时分秒初始化一个LocalDateTime对象
public class test {
    public static void main(String[] args){
        LocalDateTime time = LocalDateTime.of(2023,8,30,11,49,2);
        System.out.println(time);
        //打印结果 2023-08-30T11:49:02
    }
获取年
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime time = LocalDateTime.now();
        //获取年
        int year = time.getYear();
        System.out.println(year);
        //打印结果 2023
    }
}
获取月份
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime time = LocalDateTime.now();
        //获取月份
        int mouth = time.getMonthValue();
        System.out.println(mouth);
        //打印结果 8
    }
}
获取月份中的第几天
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime time = LocalDateTime.now();
        //获取月份中的第几天
        int result = time.getDayOfMonth();
        System.out.println(result);
        //打印结果 30
    }
}
获取一年中的第几天
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime time = LocalDateTime.now();
        //获取一年中的第几天
        int result = time.getDayOfYear();
        System.out.println(result);
        //打印结果 242
    }
}
获取星期
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime time = LocalDateTime.now();
        //获取星期
        DayOfWeek result = time.getDayOfWeek();
        System.out.println(result);
        //打印结果 WEDNESDAY
    }
}
获取小时
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime time = LocalDateTime.now();
        //获取获取小时
        int result = time.getHour();
        System.out.println(result);
        //打印结果 12
    }
}
获取分钟
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime time = LocalDateTime.now();
        //获取获取分钟
        int result = time.getMinute();
        System.out.println(result);
        //打印结果 3
    }
}
LocalDateTime()修改
时间的增加或减少
        public LocalDateTime plusYears(long years )    添加或者减去年
        public LocalDateTime plusMonths(long months)   添加或者减去月
        public LocalDateTime plusDays(long days)       添加或者减去日
        public LocalDateTime plusHours(long hours)     添加或者减去时
        public LocalDateTime plusMinutes(long minutes) 添加或者减去分
        public LocalDateTime plusSecond(long seconds)   添加或者减去秒
        public LocalDateTime plusWeeks(long weeks)     添加或者减去周

 时间的修改
        public LocalDateTime withYear(int year )   直接修改年
        public LocalDateTime withMonth(int month)  直接修改月
        public LocalDateTime withDaysOfMonth(int dayofmonth)      直接修改日期(一个月中第几天)
        public LocalDateTime withDayOfYear(int dayofyear)    直接修改日期(一年中的第几天)
        public LocalDateTime withHour(int hour)    直接修改时
        public LocalDateTime withMinutes(int minute)直接修改分
        public LocalDateTime withSecond(int second)  直接修改秒
使用方法(演示一部分)
public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime Time = LocalDateTime.now();
        System.out.println(Time);
        //打印结果 2023-08-30T15:42:21.331706600

        LocalDateTime result = Time.plusYears(1);
        System.out.println(result);
        //打印结果 2024-08-30T15:42:21.331706600
    }
}

类型转换

String了类型转化为LocalDateTime类型
public class test {
    public static void main(String[] args){
        String StrDate = "2023-08-30 12:12:12";
        
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime time = LocalDateTime.parse(StrDate,dtf);

        System.out.println(time);
        //打印结果 2023-08-30T12:12:12
    }
}

日期类型转化为String类型

public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime nowTime = LocalDateTime.now();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");

        String time = nowTime.format(dtf);

        System.out.println(time);
        //打印结果 2023-08-30 16:07:12:653
    }
}

Period(时间间隔类)(年月日)

public class test {
    public static void main(String[] args){
        //获取当前时间
        LocalDateTime nowTime = LocalDateTime.now();

       LocalDate startTime = LocalDate.of(2021,11,11);
       LocalDate endTime = LocalDate.of(2030,12,12);
       
       Period between = Period.between(startTime,endTime);
       //间隔的年
        int years = between.getYears();
        System.out.println(years);
        //打印结果 9
        
        //间隔的月份
        int months = between.getMonths();
        System.out.println(months);
        //打印的结果 1
        
        //间隔的天数
        int days = between.getDays();
        System.out.println(days);
        //打印的结果 1
        
    }

Duration(时分秒)

public class test {
    public static void main(String[] args){
        LocalDateTime startTime = LocalDateTime.of(2020,10,10,11,11,11);
        LocalDateTime endTime = LocalDateTime.of(2020,11,10,11,11,11);

        Duration between = Duration.between(startTime,endTime);

        //间隔的天数
        long days = between.toDays();
        System.out.println(days);
        //打印的结果 31

        //间隔的小时
        long hours = between.toHours();
        System.out.println(hours);
        //打印的结果 744

        //间隔的分钟
        long minutes = between.toMinutes();
        System.out.println(minutes);
        //打印的结果 44640

    }

B i g I n t e g e r 类和 B i g D e c i m a l 类 \color{red}{BigInteger类和BigDecimal类} BigInteger类和BigDecimal

BigInteger功能

  1.可以对大整数进行运算。

BigInteger加减乘除
构造方法:
        public BigInter(String value)
        //可以将整数的字符串,转化为BigInteger对象

 成员方法:
        public BigInter add(BigInter value)   超大整数加法运算
        public BigInter subtract(BigInter value)   超大整数减法运算
        public BigInter multiply(BigInter value)   超大整数乘法运算
        public BigInter divide(BigInter value)   超大整数除法运a
使用方法
add
public class test {
    public static void main(String[] args){
        BigInteger bigIntegerAdd1 = new BigInteger("200");
        BigInteger bigIntegerAdd2 = new BigInteger("100");
        BigInteger result = bigIntegerAdd1.add(bigIntegerAdd2);
        System.out.println(result);
        //打印结果 300
    }
}
subtract
public class test {
    public static void main(String[] args){
        BigInteger bigIntegerSub1 = new BigInteger("200");
        BigInteger bigIntegerSub2 = new BigInteger("100");
        BigInteger result = bigIntegerSub1.subtract(bigIntegerSub2);
        System.out.println(result);
        //打印结果 100
    }
}
multiply
public class test {
    public static void main(String[] args){
        BigInteger bigIntegerMultiply1 = new BigInteger("200");
        BigInteger bigIntegerMultiply2 = new BigInteger("2");
        BigInteger result = bigIntegerMultiply1.multiply(bigIntegerMultiply2);
        System.out.println(result);
        //打印结果 400
    }
}
divide
public class test {
    public static void main(String[] args){
        BigInteger bigIntegerDivide1 = new BigInteger("200");
        BigInteger bigIntegerDivide2 = new BigInteger("2");
        BigInteger result = bigIntegerDivide1.divide(bigIntegerDivide2);
        System.out.println(result);
        //打印结果 100
    }
}

BigDecimal类

使用场景
BigDecimal 可以对大多数浮点数进行运算,保证运算的精确性。float,double
它们在存储运算的时候,会导致数据精度的丢失。如果要保证运算的准确性,就需要使用BigDecimal
BigDecimal加减乘除
构造方法:
        public BigDecimal(String val)BigDecimal的字符串表示形式转化为 BigDecimal

 成员方法:
        public BigDecimal add(BigDecimal value)    加法运算
        public BigDecimal subtract(BigDecimal value)    减法运算
        public BigDecimal multiply(BigDecimal value)    乘法运算
        public BigDecimal divide(BigDecimal value)    除法运算(除不尽会有异常)
        public BigDecimal divide(BigDecimal divisor , int scale ,int roundingMode) 除法运算(除不尽使用该方法)

        参数说明:
            scale 精确位数
            roundingMode 取舍模式
                BigDecimal.ROUND_HALF_UP 四舍五入
                BigDecimal.ROUND_FLOOR  去尾法
                BigDecimal.ROUND_UP   进一法
使用方法
add
public class test {
    public static void main(String[] args){
        BigDecimal bigDecimalAdd1 = new BigDecimal("10");
        BigDecimal bigDecimalAdd2 = new BigDecimal("3");
        BigDecimal result = bigDecimalAdd1.add(bigDecimalAdd2);
        System.out.println(result);
        //打印结果 13
    }
}
subtract
public class test {
    public static void main(String[] args){
        BigDecimal bigDecimalSub1 = new BigDecimal("10");
        BigDecimal bigDecimalSub2 = new BigDecimal("3");
        BigDecimal result = bigDecimalSub1.subtract(bigDecimalSub2);
        System.out.println(result);
        //打印结果 7
    }
}
multiply
public class test {
    public static void main(String[] args){
        BigDecimal bigDecimalMultiply1 = new BigDecimal("10");
        BigDecimal bigDecimalMultiply2 = new BigDecimal("3");
        BigDecimal result = bigDecimalMultiply1.multiply(bigDecimalMultiply2);
        System.out.println(result);
        //打印结果 30
    }
}
divide
public class test {
    public static void main(String[] args){
        BigDecimal bigDecimalDivide1 = new BigDecimal("10");
        BigDecimal bigDecimalDivide2 = new BigDecimal("3");
        BigDecimal result = bigDecimalDivide1.divide(bigDecimalDivide2,3,BigDecimal.ROUND_FLOOR);
        System.out.println(result);
        //10/3 除不尽会报错,所以这里需要增加两个参数
        //打印结果 3.333
    }
}

正则表达式 \color{red}{正则表达式} 正则表达式

 预定义字符:简化字符类的书写

    .  :  匹配任何字符
    \d:   任何数字[0-9]的简写
    \D:   任何非数字[0-9]的简写
    \s:   空白字符:[\t\n\x0B\f\r]的简写
    \S:   非空白字符:[^\s]的简写
    \w:   单词字符:[a-zA-Z_0-9]的简写
    \W:   非单词字符:[^\w]


    数量词:
        X?  : 0次或1X*  : 0次或多次
        X+  : 1次或多次
        X{n}: 恰好n次
        X{n,}:至少n次
        X{n,m}: n到m次(n和m都是包含的)


        可以将重复出现的用小括号括起来,当作小组对待

验证str是否以h开头,以d结尾,中间是a,e,i,o,u中某个字符

public class test {
    public static void main(String[] args){
        //验证str是否以h开头,以d结尾,中间是a,e,i,o,u中某个字符
        
        String s = "hdd";
        boolean result = s.matches("h[aeiou]d");
        System.out.println(result);
        //打印结果 false
    }
}

验证str是否以h开头,以d结尾,中间不是a,e,i,o,u中某个字符

public class test {
    public static void main(String[] args){
        //验证str是否以h开头,以d结尾,中间不是a,e,i,o,u中某个字符
        String s = "hdd";
        boolean result = s.matches("h[^aeiou]d");
        System.out.println(result);
        //打印结果 true
    }
}

要求字符串是除a,e,i,o,u外的其他小写字符开头,后跟ad

public class test {
    public static void main(String[] args){
        //要求字符串是除a,e,i,o,u外的其他小写字符开头,后跟ad
        String s = "hdd";
        boolean result = s.matches("[^[aeiou]&&a-z]ad");
        System.out.println(result);
        //打印结果 false
    }
}

验证str是否是三位数字

方法1
public class test {
    public static void main(String[] args){
        String s = "123";
        boolean result = s.matches("[1-9][1-9][1-9]");
        System.out.println(result);
        //打印结果 true
    }
}
方法2
public class test {
    public static void main(String[] args){
        String s = "123";
        boolean result = s.matches("\\d\\d\\d");
        System.out.println(result);
        //打印结果 true
    }
}

验证str是否三位数

public class test {
    public static void main(String[] args){
        String s = "123";
        boolean result = s.matches("\\d{3}");
        System.out.println(result);
        //打印结果 true
    }
}

验证str是否是多位(大于等于1次)数字

public class test {
    public static void main(String[] args){
        String s = "123";
        boolean result = s.matches("\\d+");
        System.out.println(result);
        //打印结果 true
    }
}

验证str是否是手机号(1开头,第二位3/5/8,剩下都是0-9的数字)

public class test {
    public static void main(String[] args){
        String s = "15811112222";
        boolean result = s.matches("1[358]\\d{9}");
        System.out.println(result);
        //打印结果 true
    }
}

验证qq号

  1.5-15位
  2.全是数字
  3.第一位不是0

public class test {
    public static void main(String[] args){
        String s = "15456265";
        boolean result = s.matches("[1-9]\\d{4,14}");
        System.out.println(result);
        //打印结果 true
    }
}

可以将重复出现的用小括号括起来,当作小组对待

public class test {
    public static void main(String[] args){
        //可以将重复出现的用小括号括起来,当作小组对待
        String str1 = "DEFF8-DASFA-DASF8-SD85S-SAD5D";
        System.out.println(str1.matches("[0-9A-Z]{5}-[0-9A-Z]{5}-[0-9A-Z]{5}-[0-9A-Z]{5}-[0-9A-Z]{5}"));
        //打印结果 true
        System.out.println(str1.matches("([0-9A-z]{5}-){4}[0-9A-Z]{5}"));
        //打印结果 true
    }
}

迭代器 \color{red}{迭代器} 迭代器

概述

  迭代器是对Iterator的称呼,专门用来对Collection集合进行遍历是使用的。学习迭代器的目的就是为了遍历集合。

相关API的介绍

   Iterable,Iterator。

public class test {
    public static void main(String[] args){
        //创建集合对象
        Collection<String> c = new ArrayList<>();
        //添加元素
        c.add("貂蝉");
        c.add("刘备");
        c.add("张飞");

        //遍历集合
        Iterator<String> it = c.iterator();
        //hasNext判断是否有下一个元素
        while(it.hasNext()){
            String next = it.next();
            System.out.print(next+" ");
        }
        //打印的结果 貂蝉 刘备 张飞 
    }
}

自定义泛型类接口 \color{red}{自定义泛型类接口} 自定义泛型类接口

泛型类

  什么是泛型类。

先了解一下java中包括的泛型类:

public class test {
    public static void main(String[] args){
        ArrayList<String> c = new ArrayList<>();
    }
} 

熟悉吗,ArrayList<>,在上面我们介绍到过。

回忆一下,我们继续往下看。

自定义泛型类

  当定于类时,内部方法中其参数类型,返回值不确定时,就可以使用泛型替代。

public class test {
    public static void main(String[] args){
        Person<String> person = new Person<>();
    }
}

//自定义泛型类,类型
class Person<H>{
    
    private H hobby;
    
    public Person(){
        
    }
    
    public Person(H hobby){
        this.hobby = hobby;
    }
    
    public H getHobby(){
        return hobby;
    }
    
    public void setHobby(H hobby){
        this.hobby = hobby;
    }

    @Override
    public String toString() {
        return "Person{" +
                "hobby=" + hobby +
                '}';
    }
}

自定义泛型接口

什么时候使用泛型接口

   当定义接口的时候,内部方法中其参数类型,返回值不确定时,就可以使用泛型替代。

定义泛型接口的格式

  接口名后面加上尖括号,里面定义泛型名。

泛型接口中的泛型确定时机

  子类如果可以确定类型,在实现接口的时候,直接确定类型。
  子类如果不确定类型,回到泛型类的使用。

//自定义泛型接口
public interface MyCollection<E> {
    //抽象方法
    public abstract void add(E e);
}

//如果泛型没有指定,默认Object类型
class MyCollectionImpl1 implements MyCollection{

    //抽象方法必须重写
    @Override
    public void add(Object o) {

    }
}

class MyCollectionImpl2 implements MyCollection<String>{

    //抽象方法必须重写
    @Override
    public void add(String s) {

    }
}

//注意这里的细节 MyCollectionImpl3<E>
class MyCollectionImpl3<E> implements MyCollection<E>{

    //抽象方法必须重写
    @Override
    public void add(E e) {

    }
}

自定义泛型方法

  当定义方法时,方法中的参数类型,返回值类型不确定时,就可以使用泛型替代了。

定义格式
修饰符<泛型名> 返回值类型 方法名(参数类型){
}
泛型的指定

  调用含有泛型的方法的时候,传入的数据其类型就是泛型的类型。

public class test{
    public static void main(String[] args) {
        show("abc");
        //打印的结果 e is String

        show(1);
        //打印的结果 e is Integer
    }

    //自定义泛型的方法
    public static <E> void show(E e){
        if(e instanceof String){
            System.out.println("e is String");
        }

        if (e instanceof Integer){
            System.out.println("e is Integer");
        }
    }
}

定义存储字符串的ArrayList 集合,将字符串的集合转化为字符串数组

public class test{
    public static void main(String[] args) {
        //创建一个Arraylist对象
        ArrayList<String> list = new ArrayList<>();

        //给集合中添加元素
        list.add("abc");
        list.add("123");
        list.add("qwe");

        //将字符串集合转化为字符串数组
        
        //创建一个数组 数组长度为 list.size()
        String[] strings = new String[list.size()];
        // list.toArray(strings)
        String[] array = list.toArray(strings);
        System.out.println(Arrays.toString(array));
        //打印结果 [abc, 123, qwe]
    }
}

泛型通配符

泛型上限的格式和定义
<? entends 类型>  只能时本类型或者子类型
泛型下限的格式和含义
<? super 类型> 只能是本类型或者父类型,到顶只能是Object
public class test{
    public static void main(String[] args) {
        ArrayList<Integer> integers = new ArrayList<>();
        ArrayList<Number> numbers = new ArrayList<>();
        ArrayList<String> strings = new ArrayList<>();
        ArrayList<Object> objects = new ArrayList<>();
        
        
        //下限
        show1(numbers);
        show1(objects);
        
        //上限
        show2(numbers);
        show2(integers);
        
    }
    
    //泛型的下限
    //show1方法,参数只接受Number或者其父类型的集合
    public static void show1(ArrayList<? super Number> List){
        
    }
    
    //泛型的上限
    //show2方法,参数只接受我Number或者其子类型
    public static void show2(ArrayList<? extends Number> list){}
    
}

T r e e S e t \color{red}{TreeSet} TreeSet

自然排序

  自定义实现Comparable接口,重写compareTo 方法,根据返回值进行排序。

student类
public class Student implements Comparable<Student>{

    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    //需要重写 CompareTO
    @Override
    public int compareTo(Student o) {
        //根据年龄的升序排序
        //this表示当前往集合中添加的元素
        //o表示集合中已经存在的元素
        int result = this.age - o.age;

        //如果年龄一样,根据名字的升序排序
        return result==0?this.name.compareTo(o.name):result;
    }
}
ComparableDemo1
public class ComparableDemo1 {
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<>();

        Student s1 = new Student("张三",23);
        Student s2 = new Student("李四",34);
        Student s3 = new Student("王五",54);
        Student s4 = new Student("六子",23);
        Student s5 = new Student("M",11);

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        for(Student t : ts){
            System.out.println(t);
        }
        
        //打印结果
        /*
        Student{name='M', age=11}
        Student{name='六子', age=23}
        Student{name='张三', age=23}
        Student{name='李四', age=34}
        Student{name='王五', age=54}

         */
    }
}

比较器排序

  1.TreeSet的构造方法使用的是比较器排序对元素进行排序。
  2.比较器排序,就是让TreeSet集合狗杂方法接受Comparator接口的实现类对象。
  3.重写Comparator接口中的compare(T o1, T o2)方法,指定排序规则。
  4.o1代表的是当前往集合中添加的元素,o2代表的是集合中已经存在的元素,排序原理与自然排序相同!!!

Student
public class Student {

    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    
}
ComparatorDemo1
public class ComparableDemo1 {
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<>(new ComparatorImpl());

        Student s1 = new Student("张三",23);
        Student s2 = new Student("李四",34);
        Student s3 = new Student("王五",54);
        Student s4 = new Student("六子",23);
        Student s5 = new Student("M",11);

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        for(Student t : ts){
            System.out.println(t);
        }

        //打印结果
        /*
        Student{name='M', age=11}
        Student{name='六子', age=23}
        Student{name='张三', age=23}
        Student{name='李四', age=34}
        Student{name='王五', age=54}

         */
    }
}

class ComparatorImpl implements Comparator<Student> {


    @Override
    public int compare(Student o1, Student o2) {
        //根据年龄升序排序
        int result = o1.getAge()- o2.getAge();

        //年龄一样,根据姓名升序

        return result==0?o1.getName().compareTo(o2.getName()):result;
    }
}

两种排序都存在,优先使用比较器排序!!!

C o l l e c t i o n \color{red}{Collection} Collection

shuffle

  打乱List集合中元素顺序。

public class ShuffleDemo {
    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();

        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        //乱序
        Collections.shuffle(list);

        for(Integer i : list){
            System.out.println(i);
        }
        /*
        打印结果
        2
        4
        1
        3
         */
    }
}

sort

  实现自然排序和比较器排序。

方法1
public class ShuffleDemo1 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();

        list.add(5);
        list.add(6);
        list.add(2);
        list.add(3);
        list.add(8);

        //public static <T extends Comparable > void sort (List<T> list)
        Collections.sort(list);

        System.out.println(list);
    }
}

方法2
public class ShuffleDemo2 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();

        list.add(5);
        list.add(6);
        list.add(2);
        list.add(3);
        list.add(8);

        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return -o1.compareTo(o2);
            }
        });

        System.out.println(list);
    }
}

可变参数 \color{red}{可变参数} 可变参数

  1.在jdk5中提供了可变参数,有允许在调用方法时传入任意个参数。可变参数原理就是一个数组形式存在。
  格式:修饰符 返回值类型 方法名(数据类型……变量名){ }

  

public class  Test {
    public static void main(String[] args) {
        sum(new int[]{1,2,3,4});

        sum(1,2,3,4,5);
    }
    public static int sum(int...num){
        int sum=0;
        for (int i : num) {
            sum+=i;
        }
        return sum;
    }
}

M a p \color{red}{Map} Map

  里面保存的数据是成对存在的,称之为双列集合。

特点

  <K,V> K:键的数据类型;V:值的数据类型

1.键不能重复,值是可以的。
2.键和值一一对应,通过键可以找到对应的值。
3.(键+值)一起是一个整体,我们陈之为“键值对”或者“键值对对象”,在java中叫做“Entry对象”。

常用方法

put

  把指定的键与指定的值添加到Map集合中。

public class test {
    public static void main(String[] args) {
        //创建Map集合对象
        Map<String,String> map = new HashMap<>();

        //添加元素 put
        map.put("孙悟空","唐僧");
        map.put("猪八戒","唐僧");
        map.put("沙僧","唐僧");
        map.put("白龙马","唐僧");

        System.out.println(map);
        //打印结果 {白龙马=唐僧, 沙僧=唐僧, 孙悟空=唐僧, 猪八戒=唐僧}
    }
}
remove

  把指定的键所对应的键值对元素在集合中删除,返回被删除元素的值。

public class test {
    public static void main(String[] args) {
        //创建Map集合对象
        Map<String,String> map = new HashMap<>();

        //添加元素 put
        map.put("孙悟空","唐僧");
        map.put("猪八戒","唐僧");
        map.put("沙僧","唐僧");
        map.put("白龙马","唐僧");

        //删除元素 remove
        map.remove("白龙马");
        //删除键为白龙马的键值对

        System.out.println(map);
        //打印结果 {沙僧=唐僧, 孙悟空=唐僧, 猪八戒=唐僧}
    }
}
get

  根据指定的键,在集合中获取相对应的值。

public class test {
    public static void main(String[] args) {
        //创建Map集合对象
        Map<String,String> map = new HashMap<>();

        //添加元素 put
        map.put("孙悟空","唐僧");
        map.put("猪八戒","唐僧");
        map.put("沙僧","唐僧");
        map.put("白龙马","唐僧");

        // 通过键获得值  get
        String value = map.get("孙悟空");

        System.out.println(value);
        //打印结果 唐僧
    }
}
keyset

  获取集合中所有的键,存储到Set集合中。

public class test {
    public static void main(String[] args) {
        //创建Map集合对象
        Map<String,String> map = new HashMap<>();

        //添加元素 put
        map.put("孙悟空","唐僧");
        map.put("猪八戒","唐僧");
        map.put("沙僧","唐僧");
        map.put("白龙马","唐僧");

        // 存储所有的键 keySet
        Set<String> key = map.keySet();

        System.out.println(key);
        //打印结果 [白龙马, 沙僧, 孙悟空, 猪八戒]
    }
}

containsKey

  判断集合中是否有此键。

public class test {
    public static void main(String[] args) {
        //创建Map集合对象
        Map<String,String> map = new HashMap<>();

        //添加元素 put
        map.put("孙悟空","唐僧");
        map.put("猪八戒","唐僧");
        map.put("沙僧","唐僧");
        map.put("白龙马","唐僧");

        // 存储所有的键 keySet
        boolean keyExist = map.containsKey("孙悟空");
        //判断是否包含键为 孙悟空 的集合
        
        System.out.println(keyExist);
        //打印结果 true
    }
}
entrySet

  拿到键值对对象。

public class test {
    public static void main(String[] args) {
        //创建Map集合对象
        Map<String,String> map = new HashMap<>();

        //添加元素 put
        map.put("孙悟空","唐僧");
        map.put("猪八戒","唐僧");
        map.put("沙僧","唐僧");
        map.put("白龙马","唐僧");

        Set<Map.Entry<String, String>> set = map.entrySet();
        for(Map.Entry<String,String> s :set){
            String key = s.getKey();
            String value = s.getValue();
            System.out.println(key+" "+value);
        }
        //打印结果 
        /*
        白龙马 唐僧
        沙僧 唐僧
        孙悟空 唐僧
        猪八戒 唐僧
         */
    }
}

Map使用练习

  需求:统计字符串中每一个字符出现的次数。

public class test {
    public static void main(String[] args) {
        //所求字符串
      String str = "adjaksljdflksaf";
      //创建Map对象
      Map<Character,Integer> map = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            //得到字符串中的字符
            char ch = str.charAt(i);
            //判断map集合中有没有包含此字符
            if(map.containsKey(ch)){
                //存储字符,值在原来的基础加上1
                map.put(ch,map.get(ch)+1);
            }else{
                //没有包含 
                //存储字符,第一次出现所以值为1
                map.put(ch,1);
            }
        }
        StringBuilder sb = new StringBuilder();
        //键值对对象
        Set<Map.Entry<Character, Integer>> set = map.entrySet();
        for (Map.Entry<Character, Integer> entry : set) {
            //获取键
            Character key = entry.getKey();
            //获取值
            Integer values = entry.getValue();
            sb.append(key).append("(").append(values).append(")");
        }
        System.out.println(sb);
        //打印结果 a(3)s(2)d(2)f(2)j(2)k(2)l(2)
    }
}

集合嵌套 \color{red}{集合嵌套} 集合嵌套

单列集合嵌套单列集合

public class Test1 {
    public static void main(String[] args) {
        int count=0;
        //创建年纪的集合
        ArrayList<ArrayList<String>> 年级 = new ArrayList<>();

        //创建班级的集合
        ArrayList<String>1 = new ArrayList<>();
        Collections.addAll(1,"张","刘","关");
        ArrayList<String>2 = new ArrayList<>();
        Collections.addAll(2,"1","2","3");
        ArrayList<String>3 = new ArrayList<>();
        Collections.addAll(3,"a","b","c");

        //添加元素
        Collections.addAll(年级,1,2,3);

        for (ArrayList<String> 班级 : 年级) {
            for (String 姓名 : 班级) {
                System.out.println(姓名);
            }
            System.out.println("==================");
        }
    }
}

单列嵌套双列集合

public class test {
    public static void main(String[] args) {
        ArrayList<Map<String,String>> 年级 = new ArrayList<>();

        Map<String,String> s1 = new HashMap<>();
        s1.put("001","a");
        s1.put("002","b");
        s1.put("003","c");

        Map<String,String> s2 = new HashMap<>();
        s2.put("001","a1");
        s2.put("002","b2");
        s2.put("003","c3");

        Map<String,String> s3 = new HashMap<>();
        s3.put("001","a66");
        s3.put("002","b66");
        s3.put("003","c66");

        Collections.addAll(年级,s1,s2,s3);

        for(Map<String,String> 班级 : 年级){
            //班级 s1,s2,s3
            Set<String> 学号集合 = 班级.keySet();
            // 学生的键 001 002 003
            for (String s : 学号集合) {
                System.out.println(s);
            }
            System.out.println("==========");
        }
        //打印结果
        /*
        001
        002
        003
        ==========
        001
        002
        003
        ==========
        001
        002
        003
        ==========
         */
    }
}

多列嵌套多列集合

public class test {
    public static void main(String[] args) {
        HashMap<String,HashMap<String,String>> 年级 = new HashMap<>();

        HashMap<String,String> s1 = new HashMap<>();
        s1.put("001","a");
        s1.put("002","b");
        s1.put("003","c");

        HashMap<String,String> s2 = new HashMap<>();
        s2.put("001","a1");
        s2.put("002","b2");
        s2.put("003","c3");

        HashMap<String,String> s3 = new HashMap<>();
        s3.put("001","a66");
        s3.put("002","b66");
        s3.put("003","c66");

        年级.put("一班",s1);
        年级.put("二班",s2);
        年级.put("三班",s3);

        for (String 班级 : 年级.keySet()) {
            // 班级 :一班 二班 三班
            HashMap<String, String> 学生 = 年级.get(班级);
            Set<Map.Entry<String, String>> set = 学生.entrySet();
            for (Map.Entry<String, String> 一个班的学生 : set) {
                String key = 一个班的学生.getKey();
                String value = 一个班的学生.getValue();
                System.out.println( 班级+key+" "+ value);
            }
            System.out.println("==========");
        }
    }
}

斗地主案例 \color{red}{斗地主案例} 斗地主案例

public class  DouDiZhu {

    public static void main(String[] args) {
        //Integer 存储牌面值的编号
        //String 牌面值
        HashMap<Integer,String> pokers = new HashMap<>();

        zhunbei(pokers);
        //System.out.println(pokers);

        //洗牌
            //获取每一张配的编号
        Set<Integer> integers1 = pokers.keySet();
        List<Integer> integers2 = new ArrayList<>();
        //把set集合存放到List集合中
        integers2.addAll(integers1);

        //对integer2编号打乱
        Collections.shuffle(integers2);
        //System.out.println(integers2);

        //发牌
        TreeSet<Integer> person1 = new TreeSet<>();
        TreeSet<Integer> person2 = new TreeSet<>();
        TreeSet<Integer> person3 = new TreeSet<>();
        TreeSet<Integer> upPokers = new TreeSet<>();

        for (int i = 0; i < integers2.size()-3; i++) {
            if(i%3==0){
                //拿到集合中的每一个编号
                person1.add(integers2.get(i));
            }else if(i%3==1){
                person2.add(integers2.get(i));
            }else if(i%3==2){
                person3.add(integers2.get(i));
            }
        }
        //给底牌
        upPokers.add(integers2.get(51));
        upPokers.add(integers2.get(52));
        upPokers.add(integers2.get(53));

        kanpai(pokers, person1);
        kanpai(pokers, person2);
        kanpai(pokers, person3);
        kanpai(pokers, upPokers);
    }

    private static void kanpai(HashMap<Integer, String> pokers, TreeSet<Integer> person1) {
        for (Integer integer : person1) {
            String s = pokers.get(integer);
            System.out.print(s + "\t");
        }
        System.out.println();
    }

    private static void zhunbei(HashMap<Integer, String> pokers) {
        String[] colors = {"♥","♠","♣","♦"};

        String[] numbers = {"2","A","k","Q","J","10","9","8","7","6","5","4","3"};

        pokers.put(0,"大王");
        pokers.put(1,"小王");

        int count=2;

        for (String number : numbers) {
            for (String color : colors) {
               //System.out.println(color+number);
                pokers.put(count++,color+number);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

君生我老

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值