Java常用类

一、Object类

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

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

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

Object类可以储存任何对象

  • 作为参数,可以接受任何对象
  • 作为返回值,可以返回任何对象。

1. getClass()方法

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

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

package com.Suncx.common;

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 class TestStudent {
    public static void main(String[] args) {
        Student s1 = new Student("www", 20);
        Student s2 = new Student("sss", 21);
        //判断s1和s2是不是同一类型
        Class class1 = s1.getClass();
        Class class2 = s2.getClass();
        if (class1 == class2) {
            System.out.println("s1,s2属于同一类型");
        } else {
            System.out.println("s1,s2不是同一类型");
        }
    }
}

2. hashCode()方法

返回对象的哈希码值

哈希值根据对象的地址或字符串或数字使用hash算法计算出来的int类型的数值

一般情况下相同对象返回相同哈希码

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

3. toString()方法

返回该对象的字符串表示

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

//toString方法
System.out.println(s1.toString()); //com.Suncx.common.Student@1b6d3586
System.out.println(s2.toString()); //com.Suncx.common.Student@4554617c
  • 重写toString
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;
    }
    //重写 toString
    public String toString(){
        return name+":"+age;
    }
}
System.out.println(s1.toString()); //www:20
System.out.println(s2.toString()); //sss:21

4. equals()方法

比较两个对象地址是否相同

可进行覆盖,比较两个对象的内容是否相同

//equals方法
System.out.println(s1.equals(s2)); //false
Student s4 = new Student("小明",17);
Student s5 = new Student("小明",17);
System.out.println(s4.equals(s5)); //false
  • 重写步骤
    1. 比较两个引用是否指向同一对象
    2. 判断比较对象是否为null
    3. 判断两个引用指向的实际对象类型是否一致
    4. 强制类型转换
    5. 依次比较各个属性值是否相同
    @Override
    public boolean equals(Object obj) {
        //判断两个对象是否是同一个引用
        if (this == obj) {
            return true;
        }
        //判断obj是否为空
        if (obj == null) {
            return false;
        }
        //判断是否是同一个类型
//        if (this.getClass()==obj.getClass()){
//            return true;
//        }
        //instanceof可以判断对象是否为某种类型
        if (obj instanceof Student) {
            //强制类型转换
            Student s = (Student) obj;
            //比较
            if (this.name.equals(s.getName()) && this.age == (s.getAge())) {
                return true;
            }
        }
        return false;
    }

5. finalize()方法

当对象被判定为垃圾对象时,由JVM自动调用此方法,用以标记垃圾对象,进入回收队列

垃圾对象:没有有效引用指向此对象时,为垃圾对象

垃圾回收:由GC销毁垃圾对象,释放数据存储空间

自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象

手动回收机制:使用System.gc();通知JVM执行垃圾回收

二、包装类

基本数据类型所对应的引用数据类型

Object可统一所有数据,包装类的默认值是null

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

类型转换

  • 装箱与拆箱
public class demo01 {
    public static void main(String[] args) {
        //类型转换:装箱操作 把基本类型转换成引用类型
        int num1 = 18;//基本类型
        //使用Integer类创建对象
        Integer integer1 = new Integer(num1);
        Integer integer2 = Integer.valueOf(num1);
        
        //类型转换:拆箱 引用类型转换成基本类型
        Integer integer3 = new Integer(100);//创建引用类型
        int num2 = integer3.intValue();
        
        //jdk5之后,提供自动装箱和拆箱调用Integer.valueOf()
        int age = 30;
        //自动装箱
        Integer integer4 = age;
        //自动拆箱
        int age2 = integer4;
    }
}
  • 基本类型和字符串之间的转换
//基本类型和字符串之间转换
//1.基本类型转字符串
int n1 = 100;
//1.1使用+
String s1 = n1+"";
//1.2使用Integer中的toString()方法
String s2 = Integer.toString(n1);
System.out.println(s1);
System.out.println(s2);

//2.字符串转基本类型
String str = "150";
//使用Integer.parseInt()方法
int n2 = Integer.parseInt(str);
System.out.println(n2);
  • boolean
//boolean字符串形式转成基本类型,"true"--->true 非"true"--->false
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1); //true
String str3 = "true ";
boolean b2 = Boolean.parseBoolean(str3);
System.out.println(b2); //false
  • 整数缓冲区

    • java预先创建了256个常用的整数包装类型对象
    • 当integer的赋值在-127-128之间时,调用Integer.valueOf()创建对象
    • 当integer的赋值不在-127-128之间时,调用new Integer()创建对象
    • 所以才会出现下例中不同的输出结果
    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 = 100; //自动转型
            Integer integer4 = 100;
            System.out.println(integer3 == integer4); //true
    
            Integer integer5 = 200; //自动装箱 转型
            Integer integer6 = 200;
            System.out.println(integer5 == integer6); //false
        }
    }
    

三、String类

字符串是常量,创建之后不可改变

字符串字面值存储在字符串池之中,可以共享(常量共享)见例子

字符串池在方法区中

public class demo03 {
    public static void main(String[] args) {
        String name = "Hello"; //Hello常量存储在字符串池中
        name = "张三"; //张三赋值给name变量,没有修改数据,而是在字符串池中重新开辟一块空间;
        // "Hello"变成垃圾
        String name2 = "张三"; //在字符串池中寻找有没有"张三",若是有则指向它即常量共享
        
        //字符串的另一种创建方式
        String str = new String("hhhhh"); //存入堆空间 同时在常量池(方法区) 
        //即创建两个对象
        //但其实只有一个,有可能浪费空间
        String str2 = new String("hhhhh");
        System.out.println(str == str2); //false
    }
}

1. length()

返回字符串长度

String content = "javahhh";
System.out.println(content.length()); //7

2. charAt(int index)

返回某个位置字符

String content = "javahhh";
System.out.println(content.charAt(2)); //v

3. contains(String str)

判断是否包含某个子字串

String content = "javahhh";
System.out.println(content.contains("ah")); //true

4. toCharArray()

将字符串转换成数组

String str1 = "asdghiasdghihhhw";
System.out.println(Arrays.toString(str1.toCharArray()));
//[a, s, d, g, h, i, a, s, d, g, h, i, h, h, h, w]

5. indexOf(String str)

查找str首次出现的下标,存在则返回下标;不存在返回-1

String str1 = "asdghiasdghihhhw";
System.out.println(str1.indexOf("as"));//0
System.out.println(str1.indexOf("as",5));//6 某个索引之后第一次出现

6. lastIndexOf(String str)

查找字符串在当前字符串中最后一次出现的下标索引

String str1 = "asdghiasdghihhhw";
System.out.println(str1.lastIndexOf("hi"));//10

7. trim()

去掉字符串前后的空格

String str3 = "  asg fBUHHHadas ";
System.out.println(str3.trim());//asg fBUHHHadas

8. toUpperCase()

将小写转换成大写

String str3 = "  asg fBUHHHadas ";
System.out.println(str3.toUpperCase());//  ASG FBUHHHADAS
System.out.println(str3.toLowerCase());//  asg fbuhhhadas

9. endWith(String str)

判断字符串是否以str结尾

String str3 = "  asg fBUHHHadas ";
System.out.println(str3.trim());//asg fBUHHHadas
System.out.println(str3.toUpperCase());//  ASG FBUHHHADAS
System.out.println(str3.toLowerCase());//  asg fbuhhhadas
System.out.println(str3);//  asg fBUHHHadas
System.out.println(str3.endsWith("s"));//false
System.out.println(str3.endsWith(" "));//true
System.out.println(str3.startsWith("  as"));//true

10. replace(char old, char new)

用新的字符或字符串替换旧的字符或字符串

String content = "javahhh";
System.out.println(content.replace("java","python"));//pythonhhh

11. split()

对字符串进行拆分

String say = "java is the best,python   is easy";
String[] arr = say.split(" ");//意思是以空格划分
String[] arr1 = say.split("[ ,]");//意思是以空格划分或以逗号划分
String[] arr2 = say.split("[ ,]+");//意思是以空格划分或以逗号划分,可以连续出现多个空格或逗号
System.out.println(arr.length);//8
System.out.println(arr1.length);//9
System.out.println(arr2.length);//7
for(String i : arr){
    System.out.println(i);
}
System.out.println("----------------------------");
for(String i : arr1){
    System.out.println(i);
}
System.out.println("----------------------------");
for(String i : arr2){
    System.out.println(i);
}
/*
java
is
the
best,python


is
easy
----------------------------
java
is
the
best
python


is
easy
----------------------------
java
is
the
best
python
is
easy
*/

12. 补充equals/compareTo

  • equals:比较是否相等
  • compareTo:比较大小,字典表里的顺序谁在前谁在后
String s1 = "hello";
String s2 ="HELLO";
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equalsIgnoreCase(s2));//true 忽略大小写的比较

String s3 = "abc";//a:97
String s4 = "xyz";//x:120
System.out.println(s3.compareTo(s4));//-23 97-120

String s5 = "abc";
String s6 = "abcxyz";
System.out.println(s5.compareTo(s6));//-3 这个时候比长度

String案例

需求:

  • 已知String str = “this is a text”;
  • 将str中的单词单独获取出来
  • 将str中的text替换成practice
  • 在text前面插入一个easy
  • 将每个单词的首字母改成大写
public class demo04 {
    public static void main(String[] args) {
        String str = "this is a text";
        //获取单词
        String[] arr = str.split(" ");
        for(String i :arr){
            System.out.println(i);
        }
        //替换
        String str1 =str.replace("text","practice");
        System.out.println(str1);
        //插入在text前面插入一个easy
        String str2 = "easy "+str;//或者使用替换将text替换成easy text
        System.out.println(str2);

        //首字符大写
        for(int i = 0 ; i< arr.length ; i++){
            char c = arr[i].charAt(0);
            //把第一个字符转成大写
            char uppc = Character.toUpperCase(c);
            String news = uppc + arr[i].substring(1) + " ";
            System.out.print(news);
        }
    }
}

四、可变字符串:StringBuffer 、StringBuilder

StringBuffer:可变长字符串、JDK1.0提供、运行效率慢、线程安全

StringBuilder:可变长字符串、JDK5.0提供、运行效率快、线程不安全

方法:

    1. append();追加
    2. insert();增加
    3. replace();替换
    4. delete();删除
    StringBuffer sb = new StringBuffer();
    //1.append();追加
    sb.append("java厉害");
    System.out.println(sb.toString());//java厉害
    sb.append("java挺好的");
    System.out.println(sb.toString());//java厉害java挺好的
    //2.insert();增加
    sb.insert(0,"java怎么样?");
    System.out.println(sb.toString());//java怎么样?java厉害java挺好的
    //3.replace();替换 可以指定位置
    sb.replace(0,4,"python");//指定位置替换 含头不含尾
    System.out.println(sb.toString());//python怎么样?java厉害java挺好的
    //4.delete();删除
    sb.delete(0,6);
    System.out.println(sb.toString());//怎么样?java厉害java挺好的
    //清空
    sb.delete(0,sb.length());
    System.out.println(sb.toString());//输出空
    

验证StringBuilder效率高于String

//验证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; //拼接
//        }
//        long end = System.currentTimeMillis();
//        System.out.println("用时:"+(end-start)); //13850

        StringBuilder string1 = new StringBuilder();
        for (int i = 0; i < 99999; i++) {
            string1.append(i); //拼接
        }
        long end = System.currentTimeMillis();
        System.out.println("用时:"+(end-start)); //11
    }
}

五、Math类与Random类

1. Math类

Math类的方法都是静态的,Math类不能定义对象

方法名功能
static double abs(double a)返回一个double值的绝对值,基于重载技术参数还可以是int float等
static double max(double a,double b)返回两个值较大的那一个
static double min(double a,double b)返回两个值较小的那一个
static double pow(double a,double b)返回第一个参数的值,提升到第二个参数的幂
static double random()返回一个无符号的double值,大于或等于0.0且小于1.0
static double sqrt(double a)此方法返回正确舍入的一个double值的正平方根
static double cos(double a)返回一个角的三角余弦
public class demo12 {
    public static void main(String[] args) {
        //abs 绝对值
        System.out.println("绝对值:"+Math.abs(-10.4));//10.4
        //max
        System.out.println("最大值:"+Math.max(1,-11));//1
        //min
        System.out.println("最大值:"+Math.min(1,-11));//-11
        //random
        System.out.println("0-1的随机数1:"+Math.random());//0-1的随机数1:0.7601675566869854
        System.out.println("0-1的随机数2:"+Math.random());//0-1的随机数2:0.9323518712320555
        //round四舍五入,float时返回int值,double时返回long值
        System.out.println("四舍五入的值为:"+Math.round(10.1));//四舍五入的值为:10
        System.out.println("四舍五入的值为:"+Math.round(10.51));//四舍五入的值为:11
        System.out.println("2的3次方:"+Math.pow(2,3));//2的3次方:8.0
        System.out.println("2的平方根:"+Math.sqrt(2));//2的平方根:1.4142135623730951

    }
}
  • 注意:round四舍五入,float时返回int值,double时返回long值

2. Random类

java设计者在Random类的Random()构造方法中,使用当前时间初始化Random对象

方法名功能
nextInt(n)返回一个大于等于0,小于n的随机整数
nextDouble()返回一个大于等于0,小于1的随机浮点数
  • 模拟掷骰子
import java.util.Random;

class RandomDie{
    private int sides;
    private Random generator;
    public RandomDie(int s){
        sides = s;
        generator = new Random();
    }
    public int cast(){
        return 1+generator.nextInt(sides);//返回给用户合格的随机数
    }
}
public class demo13 {
    public static void main(String[] args) {
        int Num;
        RandomDie die = new RandomDie(6);
        final int TRIES = 15;
        for (int i = 0; i < TRIES; i++) {
            Num = die.cast();
            System.out.print(Num+" ");
        }
        System.out.println("");
    }
}

六、BigDecimal类

位于java.math包

作用:精确计算浮点数

创建方式:BigDecimal bd = new BigDecimal("1.0");

import java.math.BigDecimal;

public class demo07 {
    public static void main(String[] args) {
        double d1 = 1.0;
        double d2 = 0.9;
        System.out.println(d1-d2);//0.09999999999999998

        //面试题 double和float存储的是近似值
        double result = (1.4-0.5)/9;
        System.out.println(result);//0.09999999999999999

        //BigDecimal大的浮点数精确计算
        BigDecimal bd1 = new BigDecimal("1.0");//用字符串,字符串是最准确的
        BigDecimal bd2 = new BigDecimal("0.9");//用字符串,字符串是最准确的
        //减法
        BigDecimal r1 = bd1.subtract(bd2);
        System.out.println(r1);//0.1
        //减法
        BigDecimal r2 = bd1.add(bd2);
        System.out.println(r2);//1.9
        //乘法
        BigDecimal r3 = bd1.multiply(bd2);
        System.out.println(r3);//0.90
        //除法
        BigDecimal r4 = new BigDecimal("1.4")
                .subtract(new BigDecimal("0.5"))
                .divide(new BigDecimal("0.9"));
        System.out.println(r4);//1

        BigDecimal r5 = new BigDecimal("10")
                .divide(new BigDecimal("3"),3,BigDecimal.ROUND_HALF_UP);//保留三位小数,四舍五入,
        System.out.println(r5);//3.33
    }
}
  • 除法:divide(BigDecimal bd,int scal,RoundingMode mode);
    • 参数scal:指定精确到小数点后几位
    • 参数mode:
      • 指定小数部分的取舍模式,通常采用四舍五入的模式
      • 取值为BigDecimal.ROUND_HALF_UP

七、与日期时间有关的类

1.Date类

表示特定的瞬间,精确到毫秒。Date类中大部分方法都已经被Calendar类中的方法所取代

import java.util.Date;

public class demo8 {
    public static void main(String[] args) {
        //1.创建Date对象
        //今天
        Date date1 = new Date();
        System.out.println(date1.toString()); //Tue Oct 18 13:11:11 CST 2022
        System.out.println(date1.toLocaleString()); //已过时 2022-10-18 13:11:11
        //昨天
        Date date2 = new Date(date1.getTime()-(60*60*24*1000));
        System.out.println(date2.toLocaleString()); //2022-10-17 13:11:11
        //2.方法after before
        boolean b1 = date1.after(date2);
        System.out.println(b1);//true
        //3.比较compareTo()
        int d = date2.compareTo(date1);
        System.out.println(d);//-1
        //4.equals比较是否相等
        boolean b2 = date1.equals(date2);
        System.out.println(b2);//false
    }
}

2. 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 amout)按照日历规则,给指定字段添加或减少时间量
long getTimeInMillies()毫秒为单位返回该日历的时间值
import java.util.Calendar;

public class demo09 {
    public static void main(String[] args) {
        //1.创建
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getTime().toLocaleString());
        //2.获取时间信息
        int year = calendar.get(Calendar.YEAR);
        System.out.println(year);
        int month = calendar.get(Calendar.MONTH)+1;
        System.out.println(month);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);//HOUR 12小时 HOUR_OF_DAY 24小时
        System.out.println(year+"年"+month+"月"+day+"日"+hour+"时");
        //3.修改时间
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(Calendar.DAY_OF_MONTH,5);
        System.out.println(calendar2.getTime().toLocaleString());
        //4.add修改时间
        calendar2.add(Calendar.HOUR,1);//增加一小时,减少就是-1
        System.out.println(calendar2.getTime().toLocaleString());
        //5.补充方法 一个月的最大日期,最小日期
        int max = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);
        int min = calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);
        System.out.println(max+" "+min);
    }
}

3. SimpleDateFormat类

SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类

进行格式化(日期->文本)、解析(文本->日期)

  • 常用的时间模式字母:

    字母日期或时间示例
    y2022
    M年中月份08
    d月中天数10
    H一天中小时数(0-23)22
    m分钟16
    s59
    S毫秒367
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

public class demo10 {
    public static void main(String[] args) throws ParseException {
        //1.创建SimpleDateFormat对象
        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);
        //解析 把字符串转成时间
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd");
        Date date2 = sdf1.parse("1990/05/01");
        System.out.println(date2); //Tue May 01 00:00:00 CDT 1990
    }
}

八、System类

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

方法名说明
static void arraycopy(…)复制数组
static long currentTimeMillis()获取当前系统时间,返回的是毫秒值
static void gc()建议JVM赶快启动垃圾回收器回收垃圾
static void exit(int status)退出JVM,如果参数是0表示正常退出JVM,非0表示异常退出

1. arraycopy(…)

public class demo11 {
    public static void main(String[] args) {
        //arraycopy:数组复制
        //src:原数组
        //srcPos:从哪个位置开始复制
        //dest:目标数组
        //destPos:目标数组位置
        //length:复制的长度
        int[] arr = {20,18,24,16,4,6,34,21};
        int[] dest = new int[8];
        System.arraycopy(arr,2,dest,0,6);
        for (int i = 0; i < dest.length; i++) {
            System.out.println(dest[i]);
        }
    }
}

2. currentTimeMillis()

System.out.println(System.currentTimeMillis());//1666095928410

long start = System.currentTimeMillis();
for (int i = 0; i < 99999; i++) {
    for (int j = 0; j < 99999; j++) {
        int result = i+j;
    }
}
long end = System.currentTimeMillis();
System.out.println(end-start);//5 用时

3. gc()

protected void finalize() throws Throwable {
    System.out.println("回收了"+name+""+"  "+age);
}
//gc()回收垃圾
Student S1 = new Student("aaa",19);
new Student("bbb",19);
new Student("ccc",19);
System.gc();
//回收了ccc  19
//回收了bbb  19

4. exit(int status)

//退出JVM
System.exit(0);
System.out.println("程序结束了……");//这句话不会被执行
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值