ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

内部类、常用类

2021-09-22 21:01:12  阅读:91  来源: 互联网

标签:常用 String int System println out public 内部


代码块

普通代码块

直接写在方法中的代码块就是普通代码块,作用就是限制作用域

public class Demo{
public static void main(String[] args) {
    {
        // 普通代码块
        String info = "局部变量1";
        System.out.println(info);
    }
    String info = "局部变量2";
    System.out.println(info);
    }
}

构造代码块

在类当中定义的代码块,创建对象的时候执⾏,会先于构造⽅法执⾏

public class Demo{
    {
        // 构造代码块
        System.out.println("构造块");
    }
    public Demo(){
        System.out.println("构造⽅法");
    }
}

静态代码块

在类中使⽤static声明的代码块叫静态代码块,随着类的加载⽽加载,在第⼀次使⽤的时候被调⽤(创建对象),只会执⾏⼀次,优于构造块执⾏,在项⽬中常⽤于初始化只调⽤⼀次的数据。

public class Demo{
    {
        // 构造代码块
        System.out.println("构造块");
    }
    static{
        // 静态代码块
        System.out.println("静态代码块");
    }
    public Demo(){
        System.out.println("构造⽅法");
    }
}

同步代码块

内部类

定义

在一个类的内部再定义一个完整的类。

public class MyClass {
    private int num;

    class testClass {
        public void show() {
            System.out.println(num);
        }
    }
}

内部类包括:成员内部类、静态内部类、局部内部类、匿名内部类

特点

​ 1、编译之后可以生成独立的字节码文件
​ 2、内部类可直接访问外部类的私有成员,不破坏封装
​ 3、可为外部类提供必要的内部功能组件

成员内部类

定义

  1. 在类的内部定义,与实例变量、实例方法同级别的类
  2. 外部类的一个实例部分,创建内部类对象时,必须依赖外部类对象
  3. 当外部类、内部类存在重名属性,会优先访问内部类属性,如果想输出外部类成员使用:外部类.this.外部类成员
  4. 成员内部类不能定义静态成员,但是可以有静态常量

使用

  1. 内部类可以直接访问外部类的成员,包括私有
    • 外部类名.this.成员
  2. 外部类调用内部类方法,必须先创建对象
    • 内部类名 对象=内部类对象
    • 内部类 对象名=new 内部类()
public class Outer {
    //外部类⾮静态⽅法
    public void outerMethod(){
        System.out.println("外部类⽅法");
        
        //外部类调⽤内部类⽅法 必须先创建内部类对象
        Inner inner = new Inner();
        inner.innerMethod();
    }
    class Inner{
    	//内部类⾮静态⽅法
        public void innerMethod(){
        //内部类调⽤外部类⾮静态⽅法
        //Outer.this.outerMethod();
        //如果没有相同的⽅法 可以省略前缀
            outerMethod();
        }
    }
}
  1. 别的类访问内部类的成员,必须创建对象

    • 外部类名.内部类名 对象名 = 外部类对象.内部类对象

    • 外部类.内部类 对象名 = new 外部类().new 内部类()

      MyClass.testClass testClass = new MyClass().new testClass();

public class MyClass {
    //外部类成员
    private int num = 10;

    //内部类
    class testClass {
        //内部类成员
        private int sum = 55;
        private int num = 20;
        //内部静态常量
        private static final int COUNT = 100;

        //内部类方法
        public void show() {
            //输出外部类成员
            System.out.println(MyClass.this.num);
            //输出内部类成员
            System.out.println(num);
            System.out.println(sum);
        }
    }

    public static void main(String[] args) {
        //内部类变量调用内部类方法
        testClass testClass = new MyClass().new testClass();
        testClass.show();
    }
}

权限

  • 内部类的权限和成员⽅法⼀样,可以有 private 默认 protected public
  • 外部类只能是public 和 默认的
  • private 效果等同于私有化⽅法,别的类⽆法⽆法直接调⽤,但是外部类可以调⽤,可以通过⽅法return回去
  • 可以把内部类当作是⼀个类中的⽅法来看待
  • 内部类同时具有⽅法和类的所有权益
public class Outer {
    public static void main(String[] args) {
        Outer.Inner inner = new Outer().new Inner();
        inner.method();
    }

    public void method() {
        System.out.println("外部类method⽅法");
        method2();
    }

    public void method2() {
        System.out.println("外部类method2⽅法");
    }

    public class Inner {
        public void method() {
            System.out.println("内部类method⽅法");
            method2();
        }

        public void method2() {
            System.out.println("内部类method2⽅法");
            Outer.this.method2();
        }
    }
}

在这里插入图片描述

静态内部类

定义

  • 使用static关键字修饰内部类
  • 不依赖外部类对象,可直接创建或通过类名访问,可声明静态常量
  • 只能直接访问外部类的静态成员(实例成员需要实例化外部类对象)

使用

  1. 调用静态内部类内部的非静态方法

    • 外部类名.内部类名 对象名=new 外部类名.内部类名();
    public class Outer {
        //静态内部类
        public static class Inner{
            //静态内部类的⾮静态⽅法
            public void innerMethod(){
            }
        }
    }
    public static void main(String[] args) {
        //创建内部类对象
        Outer.Inner inner = new Outer.Inner();
        //调⽤内部类的⽅法
        inner.innerMethod();
    }
    
  2. 调用静态内部类内部的静态方法

    • 外部类名.内部类名.方法();
    public class Outer {
        //静态内部类
        public static class Inner{
            //静态内部类的静态⽅法
            public static void innerMethod(){
            }
        }
    }
    public static void main(String[] args) {
        //类名调⽤
        Outer.Inner.innerMethod();
    }
    
  3. 静态内部类调⽤外部类的⾮静态⽅法

    • 必须先new出外部类然后才能调⽤
    public class Outer {
        //外部类⾮静态⽅法
        public void outerMethod(){
        	System.out.println("外部类的⾮静态⽅法");
        }
        //静态内部类
        public static class Inner{
            //静态内部类⾮静态⽅法
            public void innerMethod(){
                //必须先创建外部类的对象
                new Outer().outerMethod();
            }
        }
    }
    

注意事项

  • 内部类中如果有静态⽅法,那么内部类就必须也是静态的
  • 内部类是静态的,并不意味着内部类中的⽅法都是静态的,只是说明我们可以绕过外部类对象直接找到内部类来使⽤

局部内部类

定义

  • 定义在外部类方法中,作用范围和创建对象范围仅限于当前方法
  • 局部内部类访问外部类当前方法中的局部变量时,因无法保障变量的生命周期与自身相同,变量必须修饰为final

使用

  1. 局部内部类的作⽤范围仅限于本⽅法中
  2. 局部内部类在访问他所在⽅法中的局部变量必须⽤final修饰
    • 局部内部类想要使⽤局部变量, 那么, 变量必须变成常量因为当调⽤这个⽅法时,局部变量如果没有⽤final修饰,他的⽣命周期和⽅法的⽣命周期是⼀样的,当⽅法弹栈,这个局部变量也会消失,那么如果局部内部类对象还没有⻢上消失想⽤这个局部变量,就没有了,如果⽤final修饰会在类加载的时候进⼊常量池,即使⽅法弹栈,常量池的常量还在,也可以继续使⽤
    • jdk 1.8 取消的这个定义 , 其实不是取消了, 是设置为了隐式的
public class MyClass {
    //外部类成员
    private int num = 10;

    public void show() {
        //外部方法成员
        //在jdk1.7需要添加final,1.8不需要,因为sum在局部内部类外面,然后sum消失了,但是局部内部类代码还在,会报错
        final int sum = 20;
        //局部内部类:不能添加任何访问修饰符
        class Innner {
            //局部内部类成员
            private int count = 0;
            //局部内部类静态常量
            private static final int age = 48;

            public void show2() {
                System.out.println(MyClass.this.num);
                System.out.println(sum);
                System.out.println(Innner.age);
                System.out.println(count);
            }
        }
        //因为Innner是局部内部类,所以要在外部类的外部方法中实例化局部内部类,然后调用局部内部类的方法
        Innner innner = new Innner();
        innner.show2();
    }
}

class Test {
    public static void main(String[] args) {
        //直接实例化外部内,然后外部类的外部方法会调用内部类,因为已经实例化好了
        MyClass myClass = new MyClass();
        myClass.show();
    }
}

匿名内部类

定义

没有类名的局部内部类(一切特征都与局部内部类相同)

使用

  • 必须继承一个父类或者实现一个接口
  • 定义类、实现类、创建对象的语法合并,只能创建一个该类的对象
  • 依旧会生成.class文件,只不过文件名为 类名&1.class

格式

new 类名或者接⼝名(){
    重写⽅法;
}
public class Test {
    public static void main(String[] args) {
/*      刚开始使用实现类实现接口,然后使用多态调用方法
        Usb usb=new Mouse();
        usb.sevice();*/

        //第二阶段,使用局部内部类调用方法
/*        class Fan implements Usb {
            @Override
            public void sevice() {
                System.out.println("风扇开始工作.....");
            }
        }
        Fan fan=new Fan();
        fan.sevice();*/

        //使用匿名内部类实现调用方法
        Usb usb = new Usb() {
            @Override
            public void sevice() {
                System.out.println("硬盘开始工作.....");
            }
        };
        usb.sevice();
    }
}

//接口:USB
interface Usb {
    void sevice();
}

//实现usb接口
class Mouse implements Usb {

    @Override
    public void sevice() {
        System.out.println("鼠标开始工作.....");
    }
}

Object类

定义

超类、基类,所有类的直接或间接父类,位于继承树的最顶层。

任何类,如没有书写extends显示继承某个类,都默认直接继承Object类,否则为间接继承。

Object类中所定义的方法,是所有对象都具备的方法。

Object类型可以存储任何对象。
作为参数,可接受任何对象。
作为返回值,可返回任何对象。

hashCode()

返回该对象的哈希码值

哈希值根据对象的地址或字符串或数字使用hash算法计算出来的int类型的数值。
一般情况下相同对象返回相同哈希码,不同对象的,hashCode()⼀般来说不会相同。
public int hashCode(){ }

public class Test1 {
    public static void main(String[] args) {
        Student student1 = new Student("1", 51);
        Student student2 = new Student("2", 6);
        Student student3=student1;
        System.out.println(student1.hashCode());
        System.out.println(student2.hashCode());
        System.out.println(student3.hashCode());
    }
}

在这里插入图片描述

重写hashCode()

 @Override
    public int hashCode() {
        int result = 1;
        int prime = 31;
        result = prime * result + this.age;
        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
        result = prime * result + ((getGander() == null) ? 0 : getGander().hashCode());
        return result;
    }

toString()

返回该对象的字符串表示(表现形式)。

可以根据程序需求覆盖该方法,如:展示对象各个属性值。

public String toString(){ }
示例:

public class Test1 {
    public static void main(String[] args) {
        Student student1 = new Student("1", 51);
        Student student2 = new Student("2", 6);
        System.out.println(student1.hashCode());
        System.out.println(student1.toString());
        System.out.println(student2.toString());
    }
}

在这里插入图片描述

toString输出的和hashcode值是一样的,只不过需要十进制转换
在这里插入图片描述

重写toString

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

在这里插入图片描述

equals()

默认实现为(this==obj),比较两个对象地址是否相同。
可进行覆盖,比较两个对象的内容是否相同。

public boolean equals(Object obj){
	System.out.println(student1.equals(student2));}

重写equsla()

@Override
    public boolean equals(Object obj) {
        //判断两个对象是否是同一个引用
        if (this == obj) {
            return true;
        }
        //判断obj是否为空
        if (obj == null) {
            return false;
        }
        //判断是否同一类型
        if (obj instanceof ObjectDemo) {
            //强制转换
            ObjectDemo objectDemo = (ObjectDemo) obj;
            //比较数据
            if (this.name.equals(objectDemo.name) &&
                    this.gander.equals(objectDemo.gander) &&
                    this.age == objectDemo.age) {
                return true;
            }
        }
        return false;
    }

== 和equals()的区别

  • ==是⼀个⽐较运算符号,既可以⽐较基本数据类型,也可以⽐较引⽤数据类型,基本数据类
    型⽐较的是值,引⽤数据类型⽐较的是地址值
  • equals⽅法是⼀个⽅法,只能⽐较引⽤数据类型,所有的对象都会继承Object类中的⽅法,
    如果没有重写Object类中的equals⽅法,equals⽅法和==号⽐较引⽤数据类型⽆区别,重
    写后的equals⽅法⽐较的是对象中的属性
  • equals()相等两个对象 hashCode()⼀定相同, equals不等的两个对象, hashCode()也有可
    能相同
  • 建⽴在equals和hashCode同步重写的情况下

getclass

返回引用中存储的实际对象类型

应用:通常用于判断两个引用中实际存储对象类型是否一致。

public final Class<?>getClass)}
示例:

public class Test1 {
    public static void main(String[] args) {
        Student student1 = new Student("1", 51);
        Student student2 = new Student("2", 6);
        //判断student1和student2是不是同一个类
        Class class1 = student1.getClass();
        Class class2 = student2.getClass();
        if (class1 == class2) {
            System.out.println(student1.getAge());
        }
    }
}

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;
    }
}

在这里插入图片描述

finalize()

定义

当对象被判定为垃圾对象时,由JVM自动调用此方法,用以标记垃圾对象,进入回收队列。
垃圾对象:没有有效引用指向此对象时,为垃圾对象。
垃圾回收:由GC销毁垃圾对象,释放数据存储空间。
自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象。
手动回收机制:使用System.gc();通知JVM执行垃圾回收。

    @Override
    protected void finalize() throws Throwable {
        System.out.println("回收垃圾");
    }

    public static void main(String[] args) {
        Student student1 = new Student("1", 51);
        new Student("2", 6);
        System.gc();
    }

下面的 new Student(“2”, 6);被回收了

String类

定义

String 类代表字符串。Java 程序中的所有字符串字⾯值(如 “abc” )都作为此类的实例实
现。我们可以将字符串看作是String, 但是严格严格意义上来说, String还是⼀个类,只是⽐较特
殊罢了

特殊性

  • String 类型的变量可以引⽤地址
  • String 类型的变量可以直接指向常量
  • String 对象的⻓度是不可变的,如果两个字符串拼接成⼀个字符串,其实是创建了⼀个新的字符串对象
public static void main(String[] args) {
    String str = new String();// 指向地址值
    String str2 = "abc"; //指向常量
}
public class Test {
    public static void main(String[] args) {
        //在栈里创建对象name,方法区中创建hello
        String name = "hello";
        //方法区创建zhangsan,hello依旧存在,只是没有使用
        name = "zhangsan";
        //name2地址指向的是zhangsan地址,用的是同一个zhangsan
        String name2 = "zhangsan";
        System.out.println(name == name2);

        //使用new创建字符串
        //在栈里创建s1,方法区创建java,new String在堆里面创建java
        //程序执行时,会调用堆里的java,堆里和方法区的java会合并,
        // 其中堆里的是假的,真正调用的是方法区的java
        String s1 = new String("java");
        String s2 = new String("java");
        //堆里有两个java,地址不一致
        System.out.println(s1==s2);
    }
}

构造⽅法

  • public String():空构造
  • public String(byte[] bytes):把字节数组转成字符串
  • public String(byte[] bytes,int index,int length):把字节数组的⼀部分转成字符串
  • public String(char[] value):把字符数组转成字符串
  • public String(char[] value,int index,int count):把字符数组的⼀部分转成字符串
  • public String(String original):把字符串常量值转成字符串

判断⽅法

  • boolean equals(Object obj): ⽐较字符串的内容是否相同,区分⼤⼩写
  • boolean equalsIgnoreCase(String str): ⽐较字符串的内容是否相同,忽略⼤⼩写
  • boolean contains(String str): 判断字符串中是否包含⼩字符串
  • boolean startsWith(String str): 判断字符串是否以某个指定的字符串开头
  • boolean endsWith(String str): 判断字符串是否以某个指定的字符串结尾
  • boolean isEmpty(): 判断字符串是否为空

获取⽅法

  • int length(): 获取字符串的⻓度
  • char charAt(int index): 获取指定索引位置的字符
  • int indexOf(int ch): 返回指定字符在此字符串中第⼀次出现处的索引, ch是字符的码表值
  • int indexOf(String str): 返回指定字符串在此字符串中第⼀次出现处的索引
  • int indexOf(int ch,int fromIndex): 返回指定字符在此字符串中从指定位置后第⼀次出现处的索引
  • int indexOf(String str,int fromIndex): 返回指定字符串在此字符串中从指定位置后第⼀次出现处的索引
  • int lastIndexOf 同上
  • String substring(int start):从指定位置开始复制字符串,默认到末尾
  • String substring(int start,int end):从指定位置开始到指定位置结束复制字符串

转换⽅法

  • byte[] getBytes(): 把字符串转换为字节数组

  • char[] toCharArray():把字符串转换为字符数组

  • static String valueOf(char[] chs):把字符数组转成字符串

  • static String valueOf(int i):把int类型的数据转成字符串

    注意:String类的valueOf⽅法可以把任意类型的数据转成字符串

  • String toLowerCase():把字符串转成⼩写

  • String toUpperCase():把字符串转成⼤写

  • String concat(String str):把字符串拼接

替换⽅法

  • String replace(char old,char new) : 将字符串中的⼀部分字符⽤新的代替
  • String replace(String old,String new) : 将字符串中的⼀部分字符串⽤新的代替

切割方法

  • String[] split(String regex) : 按照规则来切割字符串
  • String[] split(String regex, int limit) : 按照规则来切割字符串 limit 表示总共切成⼏段(也就是数组的⻓度)

其他方法

  • trim() : 去除字符串前后的空格
  • int compareTo(String anotherString) : 按字典顺序⽐较两个字符串(⼤⼩写)
  • int compareToIgnoreCase(String str) : 按字典顺序⽐较两个字符串(忽略⼤⼩)

StringBuffer

定义

线程安全的可变字符序列, ⼀个类似于String的字符缓冲区, 我们可以将StringBuffer看作是⼀个⾼级的String

和String的区别

  • String是⼀个不可变的字符序列,StringBuffer是⼀个可变的字符序列

构造⽅法

  • public StringBuffer():⽆参构造⽅法 默认容量是16
  • public StringBuffer(int capacity):指定容量的字符串缓冲区对象
  • public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
  • 扩容公式: 原容量<< 1 + 2

常⽤⽅法

  1. 容量和⻓度

    • public int capacity() : 返回当前容量
    • public int length() : 返回⻓度(字符数)
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer();
        //获取容量
        int capacity = buffer.capacity();
        //获取内容的⻓度
        int length = buffer.length();
        System.out.println(capacity);
        System.out.println(length);
    }
    
  2. 添加

    • public StringBuffer append(String str)

      可以把任意类型数据添加到字符串缓冲区⾥⾯,并返回字符串缓冲区本身

    • public StringBuffer insert(int offset,String str)

      在指定位置把任意类型的数据插⼊到字符串缓冲区⾥⾯,并返回字符串缓冲区本身

    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("abcd");
        buffer.append("abbc");
        System.out.println(buffer.toString());//结果:abcdabbc
        buffer.insert(2,"我爱你");//插⼊到指定位置
        System.out.println(buffer.toString());
    }
    
  3. 删除

    • public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
    • public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("abcd");
        buffer.deleteCharAt(1);//删除⻆标为1的值
        System.out.println(buffer.toString());//结果:acd
        buffer.delete(1, 2);
        System.out.println(buffer.toString());//结果:ad
    }
    
  4. 替换和反转

    • public StringBuffer replace(int start,int end,String str)从start开始到end⽤str替换
    • public StringBuffer reverse()字符串反转
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("abcd");
        //替换⼀部分内容
        buffer.replace(1, 3, "我爱你");
        System.out.println(buffer.toString());//结果:a我爱你d
        //反转
        buffer.reverse();
        System.out.println(buffer.toString());//结果:d你爱我a
    }
    
  5. 截取

    • public String substring(int start)从指定位置截取到末尾

    • public String substring(int start,int end):

      截取从指定位置开始到结束位置,包括开始位置,不包括结束位置

      返回值不再是StringBuffer本身,⽽是⼀个String

    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("abcdefg");
        //截取⼀部分,从某个⻆标开始,到结尾
        String s1 = buffer.substring(2);
        System.out.println(s1); //结果: cdefg
        //截取⼀段,从某个⻆标到某个⻆标 (不包尾)
        String s2 = buffer.substring(2,5);
        System.out.println(s2);//结果:cde
    }
    
  6. StringBuffer和String的相互转换

    • String – >StringBuffer

      通过构造⽅法:StringBuffer stringBuffer = new StringBuffer(s);

      通过StringBuffer的append⽅法:stringBuffer1.append(s); stringBuffer1.insert(0, s);

    • StringBuffer --> String

      通过toString()⽅法:String s2 = stringBuffer2.toString();

      通过subString(0,length):String s3 = stringBuffer2.substring(0);

案例

  1. 数组转成字符串

    使⽤StringBuffer将数组中的数据按照指定格式拼接成⼀个字符串

    public static void main(String[] args) {
        int[] arr = {6,5,8,7};
        StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        for (int i = 0; i < arr.length; i++) {
            if (i==arr.length-1) {
                buffer.append(arr[i]).append("]");
            }else{
                buffer.append(arr[i]).append(",");
            }
        }
        System.out.println(buffer.toString());//结果: [6,5,8,7]
    }
    
  2. 字符串反转

    从键盘录⼊⼀个字符串,对字符串进⾏反转

    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        String str = scanner.nextLine();
        StringBuffer buffer = new StringBuffer(str);
        buffer.reverse();
        System.out.println(buffer.toString());
        scanner.close();
    }
    
  3. 已知String str=lthis is a text";
    1.将str中的单词单独获取出来|
    2.将str中的text替换为practice
    3.在text前面插入一个easy
    4.将每个单词的首字母改为大写

        public static void main(String[] args) {
            String name = "this is a text";
            String[] arr = name.split(" ");
            for (String s : arr) {
                System.out.println(s);
            }
            System.out.println(name.replace("text", "practice"));
            System.out.println(name.replace("text", "easy text"));
            for (int i = 0; i < arr.length; i++) {
                char first = arr[i].charAt(0);
                char Upper = Character.toUpperCase(first);
                String news = Upper + arr[i].substring(1);
                System.out.println(news);
            }
        }
    

    在这里插入图片描述

StringBuilder

定义

StringBuilder功能等同于Stringbuffer, 线程不安全,效率⾼, 单线程下建议使⽤StringBuilder

和StringBuffer的区别

  • StringBuffer是jdk1.0版本开始的,是线程安全的,效率低
  • StringBuilder是jdk1.5版本开始的,是线程不安全的,效率⾼

包装类

定义

基本数据类型所对应的引用数据类型。
Object可统一所有数据,包装类的默认值是null。

对应关系表

基本数据类型包装类型
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

类型转换

public static void main(String[] args) {
    String str = "100";
    int num = Integer.parseInt(str);
    System.out.println(num*5); //结果: 500
}

装箱、拆箱

装箱:基本数据类型-引用数据类型
拆箱:引用数据类型-基本数据类型

    public static void main(String[] args) {

        //类型转换:装箱  基本类型-引用类型
        int num1 = 20;
        //使用Integer创建对象或者使用valueOf方法
        Integer integer = new Integer(num1);

        Integer integer1 = Integer.valueOf(num1);

        //类型转换:拆箱 引用类型 -基本类型
        Integer integer2 = new Integer(100);
        int num2 = integer2.intValue();

        //jdk1.5之后支持自动装箱、拆箱
        //自动装箱
        int count = 10;
        Integer integer3 = count;
        //自动拆箱
        int max = integer3;
    }

我们可以从class文件反编译代码上看出,在表面上看我们可以直接转换,但是在内部jdk帮我进行了valueOf和intValue处理

	public static void main(String args[])
	{
		int num1 = 20;
		Integer integer = new Integer(num1);
		Integer integer1 = Integer.valueOf(num1);
		Integer integer2 = new Integer(100);
		int num2 = integer2.intValue();
		int count = 10;
		Integer integer3 = Integer.valueOf(count);
		int max = integer3.intValue();
	}

基本类型和字符串之间转换

    public static void main(String[] args) {

        //基本类型和字符串之间转换
        //基本类型转换字符串
        int num1 = 20;
        String s1 = num1 + "";
        String s2 = Integer.toString(num1);
        String s3 = Integer.toString(num1, 16);
        //字符串转换成基本数据类型
        String str = "150";//只能数字
        int n=Integer.parseInt(str);

        //boolean与基本数据类型转:true-true   true-false
        String str2="false";
        boolean b1=Boolean.parseBoolean(str2);
        System.out.println(b1);
    }

整数缓冲区
Java预先创建了256个常用的整数包装类型对象。
在实际应用当中,对已创建的对象进行复用。

package util;

public class Test {
    public static void main(String[] args) {
        Integer integer1=new Integer(100);
        Integer integer2=new Integer(100);
        //比较地址
        System.out.println(integer1==integer2);
        //比较数据
        System.out.println(integer1.equals(integer2));
        Integer integer3=integer1;
        //3使用1的地址
        System.out.println(integer1==integer3);
        
        //自动装箱
       /* Integer integer4 = Integer.valueOf(100);
        Integer integer5 = Integer.valueOf(100);
        System.out.println(integer4 == integer5);*/
        Integer integer4=100;
        Integer integer5=100;
        System.out.println(integer4==integer5);
        //自动装箱使用的是缓存区的数值:-128到127,共256个数据,超出将无法直接使用缓存区地址
        //i >= Integer.IntegerCache.low && i <= Integer.IntegerCache.high
        Integer integer6=200;
        Integer integer7=200;
        System.out.println(integer6==integer7);
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5iuQ42R8-1632315063876)(F:\WP_千峰\BaiduNetdiskWorkspace\noteFile\Java\11、常用类\内部类、常用类.assets\image-20210921141338653.png)]

Math

定义

Math类包含⽤于执⾏基本数学运算的⽅法, 如初等指数,对数,平⽅根和三⻆函数

常用方法

  • public static int abs(int a) : 返回⼀个数的绝对值
  • public static double ceil(double a) : 返回⼤于等于参数的最⼩整数
  • public static double floor(double a) : 返回⼩于等于参数的最⼤整数
  • public static int max(int a,int b) : 获取最⼤值
  • public static double pow(double a,double b) : 计算某个数的⼏次幂
  • public static double random() : 获取⼀个⼤于等于0且⼩于1的随机数
  • public static int round(float a) : 对象⼩数四舍五⼊
  • public static double sqrt(double a) : 计算平⽅根
    public static void main(String[] args) {
        System.out.println(Math.abs(-12));      //绝对值int
        System.out.println(Math.ceil(3.14));    //向上取整double
        System.out.println(Math.floor(3.14));   //向下取整double
        System.out.println(Math.round(3.14));   //四舍五入int
        System.out.println(Math.random());      //随机数double
        System.out.println(Math.pow(3, 3));     //幂次方double
        System.out.println(Math.sqrt(4.0));     //平方根double
        System.out.println(Math.PI);            //圆周率常量
    }

BigInteger

定义

我们平时使⽤的数值类型都有⼀定的⻓度限制,当我们要运算的数超过了⻓度限制之后就⽆法使⽤了, 这时我们就可以使⽤BigInteger,他可以装载其他类型表示的任意⻓度的数值

构造方法

  • public BigInteger(String val)

成员方法

  • public BigInteger add(BigInteger augend) : 加
  • public BigInteger subtract(BigInteger subtrahend) : 减
  • public BigInteger multiply(BigInteger multiplicand) : 乘
  • public BigInteger divide(BigInteger divisor) : 除
  • public BigInteger[] divideAndRemainder(BigInteger val) : 返回除积和余数
public static void main(String[] args) {
    BigInteger bi = new BigInteger("10551020110102100");
    BigInteger bi2 = new BigInteger("100");
    System.out.println(bi.add(bi2));//10551020110102200
    System.out.println(bi.subtract(bi2));//10551020110102000
    System.out.println(bi.multiply(bi2));//1055102011010210000
    System.out.println(bi.divide(bi2));//105510201101021
}

BigDecimal

    public static void main(String[] args) {
        double a=1.0;
        double b=0.9;
        System.out.println(a-b);
        double c=(1.4-0.5)/0.9;
        System.out.println(c);
    }

为什么结果不是0.1和1?

double在内存存的是近似值,有一点点的误差,正常使用可以,但是某些场景是不行的。

定义

由于在运算的时候,float类型和double很容易丢失精度,为了能精确的表示、计算浮点数,Java提供了BigDecimal
不可变的、任意精度的有符号⼗进制数。

构造方法

  • public BigDecimal(String val)

常用方法

  • public BigDecimal add(BigDecimal augend) : 加
  • public BigDecimal subtract(BigDecimal subtrahend) : 减
  • public BigDecimal multiply(BigDecimal multiplicand) : 乘
  • public BigDecimal divide(BigDecimal divisor) : 除
public class Test2 {
    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("1.0");
        BigDecimal bigDecimal1 = new BigDecimal("0.9");
        //减法
        System.out.println(bigDecimal.subtract(bigDecimal1));
        //加法
        System.out.println(bigDecimal.add(bigDecimal1));
        //乘法
        System.out.println(bigDecimal.multiply(bigDecimal1));
        //除法(这里为了简便,使用拼接)
        BigDecimal bigDecimal2 = new BigDecimal("1.4")
                .subtract(new BigDecimal("0.5"))
                .divide(new BigDecimal("0.9"));
        System.out.println(bigDecimal2);
        //当除不尽的时候
        // 报错:java.lang.ArithmeticException: Non-terminating decimal expansion;
        /*BigDecimal bigDecimal3=new BigDecimal("10")
                .divide(new BigDecimal("3"));
        System.out.println(bigDecimal3);*/
        //这时就需要采取保留几位,以什么方法取舍:2位,四舍五入
        BigDecimal bigDecimal3=new BigDecimal("10")
                .divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP);
        System.out.println(bigDecimal3);
    }
}

Date

定义

Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法都已经被Calendar类中的方法所取代。
时间单位
1秒=1000毫秒
1毫秒=1000微秒
1微秒=1000纳秒

构造方法

  • public Date()
  • public Date(long date)

常用方法

  • public long getTime()
  • public void setTime(long time)
    public static void main(String[] args) {
        Date date = new Date();
        //显示今天时间
        System.out.println(date);
        //以****-**-** **:**:**显示时间
        System.out.println(date.toLocaleString());
        //显示昨天时间
        Date date1 = new Date(date.getTime() - 60 * 60 * 24 * 1000);
        System.out.println(date1.toLocaleString());
        //之前、之后
        System.out.println(date.after(date1));
        System.out.println(date1.before(date));
        //相互比较,返回1或者-1或者0,代表之前还是之后或者此刻
        System.out.println(date.compareTo(date1));
        System.out.println(date.toString());//表示瞬时时间的字符串 结果: Mon Oct 30 22:50:48 CST 2017
        System.out.println(date.getTime());//获取瞬时时间的毫秒值 结果:1509375048974
        date.setTime(1509379011190L);//设置时间点
        System.out.println(date.toString());//表示瞬时时间的字符串 结果:Mon Oct 30 23:56:51 CST 2017
    }

SimpleDateFormat

定义

时间格式化⼯具,以与语⾔⽆关的⽅式格式化并解析⽇期或时间

构造方法

  • public SimpleDateFormat()
  • public SimpleDateFormat(String pattern) 使⽤⼀个字符串时间格式

常用方法

  • public final String format(Date date)
  • public Date parse(String source)

时间格式标识符

字母时间或时间元素表示示例
GEra标志符TextAD
yYear1996;96
M年中的月份MonthJuly;jul;07
w年中的周数Number27
W月份中的周数Number2
D年中的天数Number196
d月份中的天数Number10
F月份中的星期Number8
E星期中的天数TextTuesday;Tue
aAm/pm 标记PM
H⼀天中的⼩时数(0-23)Number0
k⼀天中的⼩时数(1-24)Number24
Kam/pm 中的⼩时数(0-11)Number0
ham/pm 中的⼩时数(1-12)Number12
m⼩时中的分钟数Number30
s分钟中的秒数Number55
S毫秒数Number978
z时区General time zonePacific Standard Time;PST;GMT-08:00
Z时区RFC 822 time zone-0800
public static void main(String[] args) throws ParseException {
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    String format = dateFormat.format(date);
    System.out.println(format); // 结果: 2017-10-30 23:08:58
    Date date2 = dateFormat.parse("2017-05-1 10:13:22");//将字符串时间转成Date时间
    System.out.println(date2);//结果 : 2017-10-30 23:08:58
}

Calendar

定义

  • Calendar提供了获取或设置各种日历字段的方法。

构造方法

  • protected Calendar):由于修饰符是protected,所以无法直接创建该对象。

成员⽅法

方法名说明
static Calendar getinstance()使用默认时区和区域获取日历
void set(int year,int month,int date,int hourofday,int minute,int second)设置日历的年、月、日、时、分、秒。
int get(int field)返回给定日历字段的值。字段比如年、月、日等
void setTime(Date date)用给定的Date设置此日历的时间。Date-Calendar
Date getTime()返回一个Date表示此日历的时间。Calendar-Date
void add(int field,int amount)按照日历的规则,给指定字段添加或减少时间量
long getTimelnMillies()毫秒为单位返回该日历的时间值

时间字段

  • DAY_OF_MONTH 表示⼀个⽉中的某天
  • DAY_OF_WEEK表示⼀个星期中的某天
  • DAY_OF_YEAR表示当前年中的天数
  • HOUR_OF_DAY表示⼀天中的⼩时
  • YEAR表示年份
  • MONTH表示⽉份
  • WEEK_OF_MONTH 表示当前⽉中的星期数
public class Test3 {
    public static void main(String[] args) {
        //创建Calendar对象
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getTime().toLocaleString());
        //获取到现在的毫秒值
        System.out.println(calendar.getTimeInMillis());
        //获取时间信息:年月日
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        System.out.println(year + "年" + (month + 1) + "月" + day
                + "日 " + hour + "时" + minute + "分" + second + "秒");
        //修改时间
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(Calendar.DAY_OF_MONTH, 19);
        System.out.println(calendar1.getTime().toLocaleString());

        calendar1.add(Calendar.MINUTE,20);
        System.out.println(calendar1.getTime().toLocaleString());
        //可以获取最大值、最小值
        int max=calendar1.getActualMaximum(Calendar.DAY_OF_MONTH);
        int min=calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        System.out.println(max);
        System.out.println(min);
    }
}

案例

从键盘录⼊⼀个年份,判断当年是闰年还是平年(闰年的2⽉是29天 平年的2⽉是28天)

public static void main(String[] args) throws ParseException {
    Scanner scanner = new Scanner(System.in);
    System.out.println("请输⼊年份");
    int year = scanner.nextInt();
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, 2, 1);//设置⽇期,某年的3⽉1⽇
    calendar.add(Calendar.DAY_OF_MONTH, -1);//将时间减1天,就变成了2⽉的最后⼀天
    int day = calendar.get(Calendar.DAY_OF_MONTH);//获取到这⼀天在当⽉中的数值
    if (day==29) {
        System.out.println("今年是闰年");
    }else{
        System.out.println("今年是平年");
    }
    scanner.close();
}

System类

定义

System系统类,主要用于获取系统的属性数据和其他操作,构造方法私有的。

主要方法

方法名说明
static void arraycopy(…)复制数组
static long currentTimeMillis();获取当前系统时间,返回的是毫秒值
static void gc();建议JVM赶快启动垃圾回收器回收垃圾
static void exit(int status);退出jvm,如果参数是0表示正常退出jvm,非0表示异常退出jvm
public class Test5 {
    public static void main(String[] args) {
        //复制数组
        //Arrays.copyOf()也可以复制数组,但其实调用的也是arraycopy
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
         /*src 源数组
         srcPos 在源数组中的起始位置
         dest 目标数组
         destPos 在目标数据中的起始位置
         length 要复制的数组元素的数量*/
        int[] dest = new int[8];
        System.arraycopy(arr, 2, dest, 1, 3);
        for (int i = 0; i < dest.length; i++) {
            System.out.println(dest[i]);
        }

        //计算用时
        long start = System.currentTimeMillis();
        String num = "";
        for (int i = 0; i <= 999; i++) {
            num = num + i;
        }
        long end = System.currentTimeMillis();
        System.out.println("用时:" + (end - start));

        //垃圾回收
        new Student("111");
        System.gc();

        //程序退出
        System.exit(0);
        System.out.println(".......");


    }
}

class Student {
    private String name;

    public Student() {
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    protected void finalize() throws Throwable {
        System.out.println("回收了:" + name);
    }
}

总结

内部类:
    ·在一个类的内部再定义一个完整的类。
    ·成员内部类、静态内部类,局部内部类、匿名内部类
Object类:
    ·所有类的直接或间接父类,可存储任何对象。
包装类:
    ·基本数据类型所对应的引用数据类型,可以使Object统一所有数据。
String类:
    ·字符串是常量,创建之后不可改变,字面值保存在字符串池中,可以共享。
BigDecimal:
    ·可精确计算浮点数。
Date
    ·特定时间
Calendar
    ·日历
SimpleDateFormat
    ·格式化时间
System

os 在目标数据中的起始位置
length 要复制的数组元素的数量*/
int[] dest = new int[8];
System.arraycopy(arr, 2, dest, 1, 3);
for (int i = 0; i < dest.length; i++) {
System.out.println(dest[i]);
}

    //计算用时
    long start = System.currentTimeMillis();
    String num = "";
    for (int i = 0; i <= 999; i++) {
        num = num + i;
    }
    long end = System.currentTimeMillis();
    System.out.println("用时:" + (end - start));

    //垃圾回收
    new Student("111");
    System.gc();

    //程序退出
    System.exit(0);
    System.out.println(".......");


}

}

class Student {
private String name;

public Student() {
}

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

public String getName() {
    return name;
}

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

@Override
protected void finalize() throws Throwable {
    System.out.println("回收了:" + name);
}

}


## 总结

    内部类:
        ·在一个类的内部再定义一个完整的类。
        ·成员内部类、静态内部类,局部内部类、匿名内部类
    Object类:
        ·所有类的直接或间接父类,可存储任何对象。
    包装类:
        ·基本数据类型所对应的引用数据类型,可以使Object统一所有数据。
    String类:
        ·字符串是常量,创建之后不可改变,字面值保存在字符串池中,可以共享。
    BigDecimal:
        ·可精确计算浮点数。
    Date
        ·特定时间
    Calendar
        ·日历
    SimpleDateFormat
        ·格式化时间
    System
        ·系统类

标签:常用,String,int,System,println,out,public,内部
来源: https://blog.csdn.net/weixin_44119864/article/details/120422822

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有