Java中的常用类

Object类的使用

包装类概述和使用

时间类的概述和使用

String类的概述和使用

Math类的概述和使用

枚举类的概述

1-1  Object类的使用

概述:

​   Object类是所有类的超类(根父类),如果在类的声明中未使用extends关键字指明父类则默认使用java.lang.Object类

  常用方法:

​     System.gc() 垃圾回收(一般不建议自定义使用)

​     GetClass() 获取类

​     hashCode() 返回哈希值

​     toString() 转成指定的字符串类型

    ​ equals() 比较两个对象是否相等

1-2  == 和 equals()的区别  

  ==:运算符

    1. 可以使用在基本数据类型和引用数据类型中表示两个数是否相等

    2. 如果是基本数据类型:比较两个变量保存的数据是否相等(不一定类型要相同)

    3. 如果是引用数据类型:比较的是地址值是否相同

  equals():方法

    1. 不能使用在基本数据类型中,只适用于引用数据类型

    2. 作用和==是相同的,比较两个对象的地址值;

    3. 像String,Data,File,包装类都重写了equals方法,重写以后不是比较的地址,而是比较的内容是否相同

  区别:

  ==:即可以比较基本数据类型也可以比较应用数据类型,两边类型要保持一致

  equals:只能比较引用数据类型

  重写equals方法

public boolean equals(Object obj) {
        if(this == obj) {//比较当前的地址和参数obj是否相同
            return true;
        }
        if(obj instanceof Order) {//判断obj是否是Order的对象
            Order o = (Order)obj;
            //比较内容
            if(this.name .equals(o.name)  && this.id == o.id ) {
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

2-1  包装类

概述:

  针对8中基本数据类型定义相应的引用类型--包装类(封装类),又来这些类的特点就可以调用类的方法了

   基本数据类型转包装类:

        int a = 10;
        Integer b = new Integer(a);
        System.out.println(b);
        Integer int1 = new Integer("123");//只能是纯粹的数字
        System.out.println(int1);
        Float f1 = new Float(12.5f);
        System.out.println(f1);
        Boolean b1 = new Boolean(false);
        Boolean b2 = new Boolean("true123");
        System.out.println(b2);

   包装类转基本数据类型:

      包装类转换基本数据类型,调用包装类XXX的xxxValue

        Integer a1 = new Integer(111);
        int a2 = a1.intValue();
        System.out.println(a2 + 1);

   5.0以后的新特性

    int num = 10; 
    Integer num1 = num;//自动装箱操作

    int num3 = num1;//自动拆箱
    System.out.println(num3);
<!--基本数据类型,包装类 -- String类型-->

    int num1 = 10;
    String s1 = num1 + "";
    //valueof
    float f1 = 12.5f;
    String s2 = String.valueOf(f1);

<!--String 基本数据类型,--包装类 调用ParseXXX();-->

    String s4 = "123";
    int a = Integer.parseInt(s4);
    System.out.println(a + 1);

3-1  时间类

  Date:

public static void main(String[] args) {
     //创建Date的对象 Date date
= new Date(); //计算毫秒差 Date date2 = new Date(System.currentTimeMillis()); System.out.println(date); System.out.println(date2); System.out.println(date.getYear()+1900);// System.out.println(date.getMonth()+1);// System.out.println(date.getDate());////时区 System.out.println(date.toGMTString()); //我们想要的格式 System.out.println(date.toLocaleString()); Date date1 = new Date(2021, 1, 22, 14, 06); System.out.println(date1); }

  SimpleDateFormat:格式化输出日期格式

public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String f1 = sdf.format(date);
        System.out.println(f1);
    }

  Calendar:

    日历类代表的是年月日周星期上午下午。精确到毫秒的时间
 * 可以直接调用它的静态方法
 * 也可以创建它的子类,GregorianCalendar
public static void main(String[] args) {
        //他是一个抽象类需要子类对象去实现
        Calendar cal = Calendar.getInstance(); 
        /*Date date = cal.getTime();
        System.out.println(date);*/
        //获取年
        int year = cal.get(cal.YEAR);
        System.out.println(year);
        //获取月
        int mon = cal.get(cal.MONTH)+1;
        System.out.println(mon);
        //一个月中的第几天(号)
        int monthDay = cal.get(cal.DAY_OF_MONTH);
        System.out.println(monthDay);
        //一年中的第几天
        int dayOfYear = cal.get(cal.DAY_OF_YEAR);
        System.out.println(dayOfYear);
        //
        int hour = cal.get(cal.HOUR);
        System.out.println(hour);
        //
        int minute = cal.get(cal.MINUTE);
        System.out.println(minute);
        //
        int  second = cal.get(cal.SECOND);
        System.out.println(second);
        //2021年01月20日 17:01:30
        String str = year + "年" + mon + "月" + monthDay + "日"
                + hour+"时" + minute + "分" + second + "秒";
        System.out.println(str);
        System.out.println(cal.getTime());
    }
}

  DateTimeFoamatter: 格式化或解析日期时间,类似于:SimpleDateFormat

public static void main(String[] args) {
        //按照指定的格式进行日期时间的输出
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH:mm:ss");
        String f = dtf.format(LocalDateTime.now());
        System.out.println(f);
        
        //按照指定的格式进行字符串日期时间的转换--->LocalDateTime
        LocalDateTime s = LocalDateTime.parse("2021年01月20日19:19:56", dtf);
        System.out.println(s);
    }

  LocalDateTime:

package Date;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/*
 * 新增的日期时间类
 */
public class LocalTest {
    public static void main(String[] args) {
        //日期类
        LocalDate date = LocalDate.now();
        //时间类
        LocalTime time = LocalTime.now();
        //日期时间类
        LocalDateTime datetime = LocalDateTime.now();
        System.out.println(date);
        System.out.println(time);
        System.out.println(datetime);
        System.out.println("-----------------");
        //另一种比较比较规范严谨的创建方式------推荐用这种
        LocalDateTime datetime2 = LocalDateTime.now();
        //获取当前日期
        LocalDate localDate = datetime2.toLocalDate();
        System.out.println(localDate);
        //获取当前时间
        LocalTime localTime = datetime2.toLocalTime();
        System.out.println(localTime);
        System.out.println("---------------------------");
        Get();
        System.out.println("---------------------------");
        SetTime();
        System.out.println("---------------------------");
        Creat();
        
    }
    //获取指定的日期时间
    public static void Get() {
        //创建日期时间类
        LocalDateTime t1 = LocalDateTime.now();
        System.out.println(t1);
        //获取年
        int year = t1.getYear();
        System.out.println(year);
        //获取月
        int month = t1.getMonthValue();
        System.out.println(month);
        //获取日
        int day = t1.getDayOfMonth();//一个月中的第几天
        int day1 = t1.getDayOfYear();//一年中的第几天
        DayOfWeek day2 = t1.getDayOfWeek();//一周的第几天
        System.out.println(day);
        System.out.println(day1);
        System.out.println(day2);
        //获取时
        int hour =  t1.getHour();
        System.out.println(t1);
        //获取分
        int minute = t1.getMinute();
        System.out.println(minute);
        //获取秒
        int second = t1.getSecond();
        System.out.println(second);
    }
    //按照指定格式设置日期时间格式
    public static void SetTime() {
        LocalDateTime t1 = LocalDateTime.of(2021, 2, 20, 18, 46);
        System.out.println(t1);
    }
    public static void Creat() {
        LocalDate t1 = LocalDate.parse("2020-01-20");
        System.out.println(t1);
        LocalTime t2 = LocalTime.parse("18:50:15");
        System.out.println(t2);
        LocalDateTime t3 = LocalDateTime.parse("2021-12-19T12:00:59");
        System.out.println(t3);
    }
}

  DateTimeFormatter: 按照指定的格式进行日期时间的输出

package Date;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatTest {
    public static void main(String[] args) {
        //按照指定的格式进行日期时间的输出
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH:mm:ss");
        String d = "2020-03-06";
        String f = dtf.format(LocalDateTime.now());
        System.out.println(f);
        
        //按照指定的格式进行字符串日期时间的转换--->LocalDateTime
        LocalDateTime s = LocalDateTime.parse("2021年01月20日19:19:56", dtf);
        System.out.println(s);
    }
}

4-1  String类

概述:

  1.String :字符串。使用一对" "引起来表示

  2.String声明为final的,是不可被继承的(不可变的特性)

  3.String实现了Serializable接口:表示字符串是支持序列化的。 实现了Comparable接口:表示可以比较大小

  4.String内部定义了final char[] value用于存储字符串数据

4-2  String不可变性

        String s1 = "javaEE";
        String s2 = "Hadoop";
        String s3 = "javaEEHadoop";
        String s4 = "javaEE"+"Hadoop";
        String s5 = s1 + "Hadoop";
        String s6 = "javaEE" + s2;
        System.out.println(s3 == s4);//true
        System.out.println(s6 == s5);//false
        String s6 = "javaEE" + s2;
        String s7 = s5.intern();//这个方法强制要求去常量池中声明(返回值是在常量池中)
 字面量 + 字面量 = 常量池(不会存在相同内容的常量)
 字面量 + new = 堆

4-3  常用方法

          String s1 = "HelloWorld";
		System.out.println(s1.length());//返回字符串长度
		System.out.println(s1.charAt(0));//返回指定索引值
		System.out.println(s1.isEmpty());//判断是否为空(判断长度是否为0)
		String lower = s1.toLowerCase();//转成小写
		System.out.println(lower);
		System.out.println(s1.toUpperCase());//转成大写
		String s3 = " Hello World ";
		String trim = s3.trim();//去除首位空格
		System.out.println(s3);
		System.out.println(trim);
		String s4 = "Hello";
		String s5 = "hello";
		System.out.println(s4.equals(s5));//比较内容是否相同
		System.out.println(s4.equalsIgnoreCase(s5));//忽略大小写
		String s6 = "asd";
		String s7 = s6.concat(s4);
		System.out.println(s7);
		String str1 = "abd";
		String str2 = "abc";
		/**
		 * 比较两个字符串的大小,整数表示这个数大,反之相反
		 */
		System.out.println(str1.compareTo(str2));
		
	}
	//@Test
	public void test2() {
		String s1 = "我是程序员";
		String sub1 = s1.substring(2);//返回从指定索引以后的
		String sub2 = s1.substring(2, 3);//包含开头不包含结尾
		System.out.println(sub1);
		System.out.println(sub2);
	}
	@Test
	public void test3() {
		String str = "HelloWorld";
		boolean b1 = str.startsWith("He");//判断是不是以指定字符开头的
		System.out.println(b1);
		boolean b2 = str.endsWith("d");//判断是否以指定字符结尾的
		System.out.println(b2);
		boolean b3 = str.startsWith("ll",2);//判断是否以指定索引出开头的
		System.out.println(b3);
		}

4-3  字符串缓冲区(可变的字符序列)

  StringBuffer:(线程安全的,效率较低)

    增:append() 删:delete() 改:setCharAt()/replace()

    插:insert() 长度:length() 遍历:for + charAt()/toString

@Test
    public void test() {
        StringBuffer sb = new StringBuffer("abc");
        sb.append(1);//添加(相当于追加拼接)
        sb.append('1');
        sb.append('2').append('3');
        System.out.println(sb);
    //    System.out.println(sb.delete(0, 1));//删除指定位置内容
        
    //    System.out.println(sb.replace(2, 3, "D"));//转换指定内容
        
        System.out.println(sb.insert(2, false));//插入指定位置内容
        
        System.out.println(sb.length());//字符序列长度
        
        System.out.println(sb.reverse());//反转
    }

    StringBuilder:(线程不安全的,效率较高)

  效率排行:StringBuilder - StringBuffer - String

4-4  BigInteger和BigDecimal

概述:

  BigInteger可以表示不可变的任意精度的整数

  BigDecimal要求数字精度比较高(精度不会损失)

5-1  比较器

概述:

    java中的对象正常情况下我们只能进行比较操作:== 或 != 不能使用><的
   如果对对象进行排序比较大下需要使用
      Comparable或Comparator
*   使用:Comparable接口
*     像String,包装类实现了Comparable接口,重写了compareTo方法
*   重写compareto方法,默认从小到大排序
*     如果当前对象this大于形参对象obj,返回正整数
*     如果当前对象this小于形参独享obj,返回负整数
*     如果当前对象this等于形参对象obj,返回0
* 自然排序:
   自定义类需要实现comparable接口重写compareto(obj)方法,需要指明如何排序

public int compareTo(Object o) {
        if(o instanceof Goods) {
            Goods good = (Goods)o;
            if(this.price > good.price) {
                return 1;
            }else if(this.price < good.price) {
                return -1;
            }else {
                return 0;
            }
        }
        /*return 0;*/
        throw new RuntimeException("类型不一样");

  定制排序

/**
     * Comparator接口的使用:
     *定制排序
     *按照字符串从大到小排序
     */
    public void test3() {
        String []arr = new String[]                         {"AA","FF","BB","CC","DD","EE"};
        Arrays.sort(arr, new Comparator(){
            @Override
    public int compare(Object o1, Object o2) {
        if(o1 instanceof String && o2 instanceof String) {
            String s1 = (String) o1;
            String s2 = (String) o2;
            //加个-表示从大到小排序
            return -s1.compareTo(s2);
            }
            throw new RuntimeException("类型不匹配");
            }});
        System.out.println(Arrays.toString(arr));
    }

6-1  System类

  System代表系统,系统级的很多属性和控制方法都放置在该类的内部,位于java.lang包

  常用方法;

    currentTimeMillis():一般用于计时

    exit(int status):退出程序

    gc():调用垃圾回收

    getProperty(String key):获取系统中的属性

7-1  Math类

package Math;


public class MathTest {

    public static void main(String[] args) {

        System.out.println(Math.PI);//3.1415926
        
        System.out.println(Math.sqrt(16));   //4.0
        System.out.println(Math.cbrt(8));    //2.0
        System.out.println(Math.pow(3,2));     //9.0
        System.out.println(Math.max(2.3,4.5));//4.5
        System.out.println(Math.min(2.3,4.5));//2.3
 
        /**
         * abs求绝对值
         */
        System.out.println(Math.abs(-10.4));    //10.4
        System.out.println(Math.abs(10.1));     //10.1
 
        /**
         * ceil天花板的意思,就是返回大的值
         */
        System.out.println(Math.ceil(-10.1));   //-10.0
        System.out.println(Math.ceil(10.7));    //11.0
        System.out.println(Math.ceil(-0.7));    //-0.0
        System.out.println(Math.ceil(0.0));     //0.0
        System.out.println(Math.ceil(-0.0));    //-0.0
        System.out.println(Math.ceil(-1.7));    //-1.0
 
        /**
         * floor地板的意思,就是返回小的值
         */
        System.out.println(Math.floor(-10.1));  //-11.0
        System.out.println(Math.floor(10.7));   //10.0
        System.out.println(Math.floor(-0.7));   //-1.0
        System.out.println(Math.floor(0.0));    //0.0
        System.out.println(Math.floor(-0.0));   //-0.0
 
        /**
         * random 取得一个大于或者等于0.0小于不等于1.0的随机数
         */
        System.out.println(Math.random());  //小于1大于0的double类型的数
        System.out.println(Math.random()*2);//大于0小于2的double类型的数
        System.out.println(Math.random()*2+1);//大于1小于3的double类型的数
 
        /**
         * rint 四舍五入,返回double值
         * 注意.5的时候会取偶数    异常的尴尬=。=
         */
        System.out.println(Math.rint(10.1));    //10.0
        System.out.println(Math.rint(10.7));    //11.0
        System.out.println(Math.rint(11.5));    //12.0
        System.out.println(Math.rint(10.5));    //10.0
        System.out.println(Math.rint(10.51));   //11.0
        System.out.println(Math.rint(-10.5));   //-10.0
        System.out.println(Math.rint(-11.5));   //-12.0
        System.out.println(Math.rint(-10.51));  //-11.0
        System.out.println(Math.rint(-10.6));   //-11.0
        System.out.println(Math.rint(-10.2));   //-10.0
 
        /**
         * round 四舍五入,float时返回int值,double时返回long值
         */
        System.out.println(Math.round(10.1));   //10
        System.out.println(Math.round(10.7));   //11
        System.out.println(Math.round(10.5));   //11
        System.out.println(Math.round(10.51));  //11
        System.out.println(Math.round(-10.5));  //-10
        System.out.println(Math.round(-10.51)); //-11
        System.out.println(Math.round(-10.6));  //-11
        System.out.println(Math.round(-10.2));  //-10
    }

}

8-1  枚举类  (这里我也是借鉴一下,我自己也不是太能使用明白)

概述:

  类的对象只有有限个,确定的,当需要定义一组常量时,强烈建议使用枚举类

  例如:星期:星期一...星期日

  自定义枚举类:

package 枚举类;
/*
 * 1.枚举类的使用:
 * 类的对象有有限个,确定的我们称此类为枚举类
 * 2.如何定义枚举类;
 * 2.1:jdk5.0之前自定义枚举类
 * 2.2:jdk5.0时可以使用enum关键字定义枚举类
 * eunm常用方法:
 * values():返回枚举类型的对象数组,遍历所有值
 * valueOf():可以把一个字符串转换为对应的枚举类对象,字符串必须是枚举类对象的名字
 * toString():返回当前枚举类对象常量的名字
 */
public class Test01 {
    public static void main(String[] args) {
        System.out.println(Season.AUTUMU);
    }
}
//自定义枚举类
class Season {//季节
    //1.声明Season对象的属性,定义成常量
    private final String name;
    private final String desc;
    //2.私有化类的构造器,给对象赋值
    private Season(String name,String desc){
        this.name = name;
        this.desc = desc;
    }
    //3.提供当前枚举类的多个对象,声明为公共的
    public static final Season SPRING = new Season("春天","春暖花开");
    public static final Season SUMMER = new Season("夏天","夏日炎炎");
    public static final Season AUTUMU = new Season("秋天","秋风徐徐");
    public static final Season WINTER = new Season("冬天","冰天雪地");
    
    //4.获取对象的属性
    public String getName() {
        return name;
    }
    public String getDesc() {
        return desc;
    }
    //提供toString方法

    public String toString() {
        return "Season [name=" + name + ", desc=" + desc + "]";
    }
    
}

  使用关键字enum

package 枚举类;
/*
 * 使用enum
 * 定义的枚举类默认继承class java.lang.Enum
 */
public class Test02 {
    public static void main(String[] args) {
        Season1 summer = Season1.SUMMER;
        System.out.println(summer.toString());
        //System.out.println(summer.getClass().getSuperclass());
        System.out.println();
        //values()
        Season1[] values = Season1.values();
        for (int i = 0; i < values.length; i++) {
            System.out.println(values[i]);
        }
        
        System.out.println();
        //valueOf(),根据参数返回与之相同的参数名
        Season1 valueOf = Season1.valueOf("WINTER");
        System.out.println(valueOf);
    }
}
//使用enum关键字来定义
enum Season1{//季节
    //1.提供当前枚举类的对象,多个对象之间用逗号隔开,末尾分号结束
     SPRING ("春天","春暖花开"),
     SUMMER ("夏天","夏日炎炎"),
     AUTUMU ("秋天","秋风徐徐"),
     WINTER ("冬天","冰天雪地");
    //1.声明Season对象的属性,定义成常量
    private final String name;
    private final String desc;
    //2.私有化类的构造器,给对象赋值
    private Season1(String name,String desc){
        this.name = name;
        this.desc = desc;
    }
    
    //4.获取对象的属性
    public String getName() {
        return name;
    }
    public String getDesc() {
        return desc;
    }
    //提供toString方法

    /*public String toString() {
        return "Season [name=" + name + ", desc=" + desc + "]";
    }*/
    
}
原文地址:https://www.cnblogs.com/wyk1/p/14427702.html