Java常用类合集

Java常用类合集

Object类概述

Object类

  1. 超类、基类,所有类的直接或间接父类,位于继承树的最顶层
  2. 任何类,如没有书写extends显示继承某个类,都默认直接继承Object类,否则为间接继承
  3. Object类中所定义的方法,是所有对象都具备的方法
  4. Object类型可以存储任何对象
    1. 作为参数,可接受任何对象
    2. 作为返回值,可返回任何对象

getClass()方法

  1. publice final Class<?> getClass(){}
  2. 返回引用中存储的实际对象类型
  3. 应用:通常用于判断两个引用中实际存储的对象类型是否一致

代码如下:

public class Student {
    private String name;
    private int age;

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

public class TestStudent {
    public static void main(String[] args) {
        Student s1 = new Student("aaa", 20);
        Student s2 = new Student("bbb", 22);
//        判断s1和s2是不是同一个类型
        Class Class1 = s1.getClass();
        Class Class2 = s2.getClass();
        if (Class1 == Class2) {
            System.out.println("s1和s2属于同一个类型");
        } else {
            System.out.println("s1和s2不属于同一个类型");
        }
    }
}
/*
 * 输出结果:s1和s2属于同一个类型
 */

hashCode()方法

  1. public int hashCode(){}
  2. 返回该对象的哈希码值
  3. 哈希值根据对象的地址或字符串或数字使用hash算法计算出来的int类型的数值
  4. 一般情况下相同对象返回相同哈希码

代码片段如下:

public class TestStudent {
    public static void main(String[] args) {
//        getClass方法
        Student s1 = new Student("aaa", 20);
        Student s2 = new Student("bbb", 22);
//        判断s1和s2是不是同一个类型
        Class Class1 = s1.getClass();
        Class Class2 = s2.getClass();
        if (Class1 == Class2) {
            System.out.println("s1和s2属于同一个类型");
        } else {
            System.out.println("s1和s2不属于同一个类型");
        }

//        hashCode方法
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        Student s3=s1;
        System.out.println(s3.hashCode());
    }
}

toString()方法

  1. public String toString(){}
  2. 返回该对象的字符串表示(表现形式)
  3. 可以根据程序需求覆盖该方法,如:展示对象各个属性值
//        3.toString方法
        System.out.println("---------------3toString------------");
        System.out.println(s1.toString());
        System.out.println(s2.toString());
//可重写
public String toString() {
        return name+":"+age;
    }

equals()方法

  1. Public boolean equals(Object boj){}
  2. 默认实现为(this == obj),比较两个对象地址是否相同
  3. 可进行覆盖,比较两个对象的内容是否相同。

equals()方法覆写步骤

  1. 比较两个引用是否指向同一个对象
  2. 判断obj是否为null
  3. 判断两个引用指向的实际对象类型是否一致
  4. 强制类型转换
  5. 依次比较各个属性值是否相同

方法复写代码

@Override
    public boolean equals(Object obj) {
//        1.判断两个对象是否是同一个引用
        if (this==obj){
            return true;
        }
//        2.判断obj是否null
        if (obj==null){
            return false;
        }
//        3.判断是否是同一个类型
//        if (this.getClass()==obj){
//
//        }
//        instanceof 判断对象是否是某种类型
        if (obj instanceof Student){
//            4.强制类型转换
            Student s=(Student)obj;
//            5.比较熟悉,这里的equals的比较是字符串的比较了,不是对象(方法的重载)
            if (this.name.equals(s.getName())&&this.age==s.age){
                return true;
            }
        }
        return false;
    }

//        4.equals方法:判断两个对象是否相等
        System.out.println("---------------4equals------------");
        System.out.println(s1.equals(s2));
        Student s4 = new Student("小明",17);
        Student s5 = new Student("小明",17);
        System.out.println(s4.equals(s5));

finalize()方法

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

代码如下

 //代码的重写
@Override
    protected void finalize() throws Throwable {
        System.out.println("对象被回收了");
    }
//控制台
public class TestStudent2 {
    public static void main(String[] args) {
//        Student s1 = new Student("aaa",20);
//        Student s2 = new Student("bbb",20);
//        Student s3 = new Student("ccc",20);
//        Student s4 = new Student("bbb",20);
//        Student s5 = new Student("ddd",20);
        new Student("aaa", 20);
        new Student("bbb", 20);
        new Student("ccc", 20);
        new Student("bbb", 20);
        new Student("ddd", 20);
//        回收垃圾
        System.gc();
        System.out.println("回收垃圾");
    }
}


包装类

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

截图

类型转换与装箱、拆箱

  1. 装箱就是将基本类型转换为引用类型
  2. 拆箱就是将堆里的引用类型转换为栈里的基本类型

代码片段如下:

public class Demo01 {
    public static void main(String[] args) {
//        类型转换:装箱,基本类型转成引用类型的的过程
//        基本类型
        int num1 = 18;
//       使用Integer类创建对象
        Integer integer1 = new Integer(num1);
        Integer integer2 = Integer.valueOf(num1);
        System.out.println("装箱");
        System.out.println(integer1);
        System.out.println(integer2);
//        类型转换:拆箱,引用类型转成基本类型
        Integer integer3 = new Integer(100);
        int i = integer3.intValue();
        System.out.println("拆箱");
        System.out.println(i);


//        JDk1.5之后,提供自动装箱和拆箱
        int age =30;
//        自动装箱
        Integer integer4 = age;
        System.out.println("自动装箱");
        System.out.println(integer4);
//        自动拆箱
        int age2 =integer4;
        System.out.println("自动拆箱");
        System.out.println(age2);
    }
}

基本类型和字符串转换

  1. 8种包装类提供不同类型间的转换方式
    1. Number父类中提供的6个共性方法
    2. parseXXX()静态方法
    3. Value()静态方法基本类型转成引用类型

代码片段如下:

        System.out.println("-------基本类型和字符串之间转换------");
//        基本类型和字符串之间转换
//        1 基本类型转成字符串
        int n1 =100;
//        1.1使用+号
        String s1 =n1+"";
//        1.2使用Integer中的toString()方法
        String s2 = Integer.toString(n1);
        String s3 = Integer.toString(n1,16);//将int转换为16进制
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);

//        2字符串转成基本类型
        String str = "150";
//        使用Integer.parseXXX()
        int n2 = Integer.parseInt(str);
        System.out.println(n2);

//        boolean类型字符串转成基本类型,"true"--->true  非"true"--->false
        String str2 ="true";
        boolean b1 =Boolean.parseBoolean(str2);
        System.out.println(b1);

    }

Integer缓冲区

  • Java预先创建了256个常用的整数包装
  • 在实际应用当中,对已创建的对象进行复用
public class Demo02 {
    public static void main(String[] args) {
//        面试题
        Integer integer1 = new Integer(100);
        Integer integer2 = new Integer(100);
        System.out.println(integer1 == integer2);//false

        Integer integer3 = Integer.valueOf(100);//自动装箱Integer.valueOf
        Integer integer4 = Integer.valueOf(100);
        //true 是因为有一个缓冲区,-128-127,如果赋予的数字在这个范围,
        // 那么valueOf就会取那个数组的地址给引用值,如果超出了范围,则会自己生成一个Integer对象,
        System.out.println(integer3==integer4);

        Integer integer5 =Integer.valueOf(200);//自动装箱
        Integer integer6 =Integer.valueOf(200);
        System.out.println(integer5==integer6);//false
    }
}

String概述

  • 字符串是常量,创建之后不可改变
  • 字符串字面值存储在字符串池中,可以共享
  • String s ="Hello";产生一个对象,字符串池中存储
  • String s = new String("Hello");//产生两个对象,堆、池各存储一个

代码片段如下:

public class Demo03 {
    public static void main(String[] args) {
        String name = "hello";//"hello"常量存储在字符串池中,
        name = "zhangsan";//在字符串池又重新开辟了一个空间,name指向zhangsan,hello变垃圾,因为无引用指向
        String name2 ="zhangsan";//会在字符串寻找有无zhangsan,有,就会指向zhangsan
//        演示字符串的另一种方式
//        在字符串池有一个,堆里有一个对象,引用指向的是堆里的,堆里的指向字符串池的
        String str =new String("Java是最好的编程语言");
        String str2 =new String("Java是最好的编程语言");
        System.out.println(str==str2);//false
        System.out.println(str.equals(str2));//string重写了equals不再是比较地址,而是比较值
    }
}

String常用方法(1)

  • public int length():返回字符串的长度
  • public char charAt(int index):根据下标获取字符
  • pubilc boolean contains(String str):判断当前字符串中是否包含str

代码片段如下

//        字符串方法的使用
//        1.length();返回字符串的长度
//        2.charAt(int index);返回某个位置的字符
//        3.contains(String str);判断是否包含某个子字符串

        String content = "java是世界上最好的编程语言";
        System.out.println(content.length());
        System.out.println(content.charAt(content.length()-1));
        System.out.println(content.contains("java"));
        System.out.println(content.contains("php"));

String常用方法(2)

  • Public char[] toCharArray():将字符串转换成数组
  • public int indexOf(String str):查找str首次出现的下标,存在,则返回该下标;不存在,则返回-1
  • pullic int lastIndexOf(String str):查找字符串在当前字符串中最后一次出现的下标索引

代码片段如下

        System.out.println("--------------字符串的使用方法2-----------------");
//        字符串方法的使用
//        4.toCharArray();返回字符串对应的数组
//        5.indexOf();返回子字符串首次出现的位置
//        6.lastIndexOf();返回字符串最后一次出现的位置
        System.out.println(Arrays.toString(content.toCharArray()));
        System.out.println(content.indexOf("java"));
        System.out.println(content.indexOf("java", 4));
        System.out.println(content.lastIndexOf("java"));

String常用方法(3)

  • public String trim():去掉字符串前后的空格
  • public String toUpperCase():将小写转成大写
  • public boolean endWith(String str):判断字符串是否以str结尾

代码片段如下

        System.out.println("--------------字符串的使用方法3-----------------");
//        7、trim();去掉字符串前后的空格
//        8、toUpperCase();//把小写转成大写toLowerCase();把大写转成小写
//        9、endWith();判断是否已str结尾,startWith(str);判断是否已str开头
        String content2 = "   hello world   ";
        System.out.println(content2.trim());
        System.out.println(content2.toUpperCase());
        System.out.println(content2.toLowerCase());
        String filename = "hello.java";
        System.out.println(filename.endsWith(".java"));
        System.out.println(filename.startsWith("hello"));

String常用方法(4)

  • Public String replace(char oldChar, char newChar):将旧字符串替换成新字符串
  • public String[] split(String str):根据str拆分

代码片段如下

        System.out.println("--------------字符串的使用方法4-----------------");

//        10、replace(char old,char new);用新的字符或字符串替换旧的的字符或字符串
//        11、split();对字符串进行拆分
        System.out.println(content.replace("java", "php"));
        String say = "java is the best programing language,java xiang";
//        如果要同时用空格和逗号来拆分就在参数里面填[ ,]如果有多个空格就在后面加个+
        String[] arr = say.split(" ");
        System.out.println(arr.length);
        for (String string:arr) {
            System.out.println(string);
        }
//        补充两个方法equals  compare();比较大小
        System.out.println("--------------补充-----------------");
        String s1 = "hello";
        String s2 = "HELLO";
        System.out.println(s1.equals(s2));
        System.out.println(s1.equalsIgnoreCase(s2));//忽略大小写的比较

        String s3 = "abc";//a:97
        String s4 = "xyz";//x:120
        System.out.println(s3.compareTo(s4));//输出-23(s3的位置-s4)
        String s5 = "abc";
        String s6 = "abcxyz";
        System.out.println(s5.compareTo(s6));//长度不一样比的就是字符数

String案例演示

  • 需求:

    • 已知String str = "this is a text";
      1. 将str中的单词单独获取出来
      2. 将str中的text替换为parctice
      3. 在text前面插入一个easy
      4. 将每个单词的首字母改为大写
    /*
    * - 需求:
      - 已知String str = "this is a text";
      - 1. 将str中的单词单独获取出来
        2. 将str中的text替换为practice
        3. 在text前面插入一个easy
        4. 将每个单词的首字母改为大写
    
    */
    public class Demo04 {
        public static void main(String[] args) {
            String str = "this is a text";
    //        1将str中的单词单独获取出来
            String[] arr = str.split(" ");
            System.out.println("1.将str中的单词单独获取出来");
            for (String s : arr) {
                System.out.println(s);
            }
    //        2将str中的text替换为practice
            System.out.println("2将str中的text替换为practice");
            String str2 = str.replace("text", "practice");
            System.out.println(str2);
    //        3. 在text前面插入一个easy
            System.out.println("3. 在text前面插入一个easy");
            String str3 = str.replace("text", "easy text");
            System.out.println(str3);
    //        4. 将每个单词的首字母改为大写
            for (int i = 0; i < arr.length; i++) {
                char first = arr[i].charAt(0);
    //            把第一个字符转成大写
                char upperfirst = Character.toUpperCase(first);
                String news = upperfirst + arr[i].substring(1);
                System.out.println(news);
            }
        }
    }
    
    

    StringBuffer和StringBuilder

    可变字符串

    • StringBuffer:可变长字符串,JDK1.0提供,运行效率慢、线程安全
    • StringBuilder:可变长字符串,JDk5.0提供,运行效率快、线程不安全
/*
*
* StringBuffer和StringBuilder的使用
* 和String区别(1)效率比String高(2)比String节省内存*/

public class Demo05 {
    public static void main(String[] args) {
//        换成StringBuilder也可行
        StringBuffer sb = new StringBuffer();
//        1 append();追加
        sb.append("java世界第一");
        System.out.println(sb.toString());
        sb.append("java真香");
        System.out.println(sb.toString());
        sb.append("java不错");
        System.out.println(sb.toString());
//        2 insert();添加
        sb.insert(0,"我在最前面");
        System.out.println(sb.toString());
//        3 replace() 含头不含尾
        sb.replace(0,5,"hello");
        System.out.println(sb.toString());
//        4 delete() 删除
        sb.delete(0,5);
        System.out.println(sb.toString());
//        5 反转
        sb.reverse();
        System.out.println(sb.toString());
//        6 清空
        sb.delete(0,sb.length());
        System.out.println(sb.length());
    }
}

//验证StringBuilder效率高于String
public class Demo06 {
    public static void main(String[] args) {
//        开始时间
        long start = System.currentTimeMillis();
//        String string = "";
//        for (int i = 0; i < 99999; i++) {
//            string+=i;
//
//        }
//        System.out.println(string);
//        用StringBuilder来实现
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 99999; i++) {
            sb.append(i);
        }
        System.out.println(sb.toString());
        long end = System.currentTimeMillis();
        System.out.println("用时:" + (end - start));
    }
}

BigDecima的使用

  • 位置:java.math包中
  • 作用:精确计算浮点数
  • 创建方式:BigDecimal bd =new BigDecimal("1.0");
  • 除法:divide(BigDecimall bd,int scale,RoundingMode mode)
  • 参数scal:指定精确到小数点后几位
  • 参数mode:
    • 指定小数部分的取舍模式,通常采用四舍五入的模式
    • 取值为bigDecimal.ROUND_HALF_UP
public class Demo07 {
    public static void main(String[] args) {
        double d1 = 1.0;
        double d2 = 0.9d;
        System.out.println(d1-d2);
//        面试题
        double result = (1.4-0.5)/0.9;
        System.out.println(result);
//        BigDecimal,大大浮点数精确计算
        BigDecimal bd1 = new BigDecimal("1.0");
        BigDecimal bd2 = new BigDecimal("0.9");
//        减法
        BigDecimal r1 = bd1.subtract(bd2);
        System.out.println(r1);
//        加法
        BigDecimal r2 = bd1.add(bd2);
        System.out.println(r2);
//       乘法
        BigDecimal r3 = bd1.multiply(bd2);
        System.out.println(r3);
//        除法
        BigDecimal r4 = new BigDecimal("1.4").subtract(new BigDecimal("0.5"))
                .divide(new BigDecimal("0.9"));
        System.out.println(r4);
//        除不尽就要植入模式
        BigDecimal r5 = new BigDecimal("10").divide(new BigDecimal("3"), 2, BigDecimal.ROUND_HALF_UP);
        System.out.println(r5);
    }
}

Date类

  • Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法都已经被Calendar类中的方法所取代
  • 时间单位
    • 1秒=1000毫秒
    • 1毫米=1000微妙
    • 1微妙=1000纳秒
public class Demo08 {
    public static void main(String[] args) {
//        1创建Date对象
//        今天
        Date date1 = new Date();
        System.out.println(date1.toString());
        System.out.println(date1.toLocaleString());
//        昨天
        Date date2 = new Date(date1.getTime() - 60 * 60 * 24 * 1000);
        System.out.println(date2.toLocaleString());
//        2方法 after before
        boolean b1 = date1.after(date2);
        System.out.println(b1);
        boolean b2 = date1.before(date2);
        System.out.println(b2);
//        比较 compareTo();
        int d1 = date1.compareTo(date2);
        System.out.println(d1);
        int d2 = date2.compareTo(date1);
        System.out.println(d2);

//        比较是否相等
        boolean b3 = date1.equals(date2);
        System.out.println(b3);
    }
}

Calendar

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

  • 构造方法

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

    图片

public class Demo09 {
    public static void main(String[] args) {
//        1创建Calendar对象
        Calendar calendar1 = Calendar.getInstance();
        System.out.println(calendar1.getTime().toLocaleString());
        System.out.println(calendar1.getTimeInMillis());
//        2获取时间信息
//        获取年
        int year = calendar1.get(Calendar.YEAR);
//        月 从0-11
        int month = calendar1.get(Calendar.MONTH);
//        日
        int day = calendar1.get(Calendar.DAY_OF_MONTH);//Date
//        小时
        int hour = calendar1.get(Calendar.HOUR_OF_DAY);//HOUR12小时,HOUR_OF_DAY 24小时
//        分钟
        int minute = calendar1.get(Calendar.MINUTE);
//        秒
        int second = calendar1.get(Calendar.SECOND);
        System.out.println(year + "年" + (month + 1) + "月" + day + "日" + hour + ":" + minute + ":" + second);
//        修改时间
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(Calendar.DAY_OF_MONTH, 20);
        System.out.println(calendar2.getTime().toLocaleString());

//        4 add方法修改时间
        calendar2.add(Calendar.HOUR,1);
        System.out.println(calendar2.getTime().toLocaleString());
//        5补充方法
        calendar2.add(Calendar.MONTH,1);
        int max = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);
        int min = calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);
        System.out.println(max);
        System.out.println(min);


    }
}

SimpleDateFormat

  • SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类
  • 进行格式化(日期->文本)、解析(文本->日期)
  • 常用的时间模式字母

图片

public class Demo10 {
    public static void main(String[] args) throws Exception{
//        1创建SimpleDateFormat对象 y 年 M 月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
//        2创建Date
        Date date = new Date();
//        格式化date(把日期转成字符串)
        String str = sdf.format(date);
        System.out.println(str);
//        解析 (把字符串转成日期)
        Date date2 = sdf.parse("1990年05月01日11:12:11");
        System.out.println(date2);

    }
}

System类

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

public class Demo11 {
    public static void main(String[] args) {
//        arraycopy: 数组的复制
//        src:源数组
//        srcPos:从哪个位置开始复制0
//        dest:目标数组
//        destPos:目标数组的位置
//        length:复制的长度
        int[] arr= {20,18,15,8,35,26,45,90};
        int[] dest= new int[8];
        System.arraycopy(arr,0,dest,0,arr.length);
        for (int i = 0; i < dest.length; i++) {
            System.out.println(dest[i]);
        }
//        Arrays.copyOf(original,newLength)
        System.out.println(System.currentTimeMillis());

        long start = System.currentTimeMillis();
        for (int i = -99999999; i < 999999; i++) {
            for (int j = -999999999; j < 999999; j++) {
                int result = i+j;
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("用时"+(end - start));
//        System.gc();告诉垃圾回收器回收

//        4推出jvm
        System.exit(0);
        System.out.println("程序结束了。。。。");
    }
}

posted @ 2021-02-21 16:31  武藤游戏_ov  阅读(38)  评论(0)    收藏  举报