02-JAVA常用类

1.Object

Object是超类:String中的equals()重写过了。Object的equals()是采用"=="进行比较的。而"=="可以比较基本数据类型(比较相等)和引用数据类型(比较引用地址相等)。
Objects是工具类。

Object的API:
protected Object clone():创建并返回一个对象的拷贝。
boolean equals(Object obj):比较两个对象是否相等。
protected void finalize():当 GC (垃圾回收器)确定不存在对该对象的有更多引用时,由对象的垃圾回收器调用此方法。
Class<?> getClass():获取对象的运行时对象的类。
int hashCode():获取对象的 hash 值。
void notify():唤醒在该对象上等待的某个线程。
void notifyAll():唤醒在该对象上等待的所有线程。
String toString():返回对象的字符串表示形式。
void wait():让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
void wait(long timeout):让当前线程处于等待(阻塞)状态,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过参数设置的timeout超时时间。
void wait(long timeout, int nanos):
与 wait(long timeout) 方法类似,多了一个 nanos 参数,这个参数表示额外时间(以纳秒为单位,范围是 0-999999)。 所以超时的时间还需要加上 nanos 纳秒。

Objects实例:

public class Test {
        public static void main(String[] args) {
             String s1 = null;
             String s2 = "sss";
             System.out.println(s1.equals(s2));
             //很多方法里考虑了对象是null的情况,在输入的参数是null时有特定的处理方式。
             Boolean result = Objects.equals(s1,s2);
             System.out.println(result);
        }
    }

2.Date

  • Date(): 构造函数使用当前日期和时间来初始化对象。
  • Date(long millisec):构造函数接收一个参数,该参数是从1970年1月1日起的毫秒数。
boolean after(Date date):若当调用此方法的Date对象在指定日期之后返回true,否则返回false。
boolean before(Date date):若当调用此方法的Date对象在指定日期之前返回true,否则返回false。
Object clone( ):返回此对象的副本。
int compareTo(Date date):比较当调用此方法的Date对象和指定日期。两者相等时候返回0。调用对象在指定日期之前则返回负数。调用对象在指定日期之后则返回正数。
int compareTo(Object obj):若obj是Date类型则操作等同于compareTo(Date) 。否则它抛出ClassCastException。
boolean equals(Object date):当调用此方法的Date对象和指定日期相等时候返回true,否则返回false。
long getTime( ):返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
int hashCode( ): 返回此对象的哈希码值。
void setTime(long time):用自1970年1月1日00:00:00 GMT以后time毫秒数设置时间和日期。
String toString( ):把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat)。

实例:

import  java.util.*;
import java.text.*;
public class DateDemo {
   public static void main(String args[]) {
      Date dNow = new Date();
      SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
      System.out.println("当前时间为: " + ft.format(dNow));
   }
}

3.Calendar

Calendar类是一个抽象类,在实际使用时实现特定的子类的对象,创建对象的过程对程序员来说是透明的,只需要使用getInstance方法创建即可。

Calendar c1 = Calendar.getInstance();
// 获得年份
int year = c1.get(Calendar.YEAR);
// 获得月份
int month = c1.get(Calendar.MONTH) + 1;
// 获得日期
int date = c1.get(Calendar.DATE);
// 获得小时
int hour = c1.get(Calendar.HOUR_OF_DAY);
// 获得分钟
int minute = c1.get(Calendar.MINUTE);
// 获得秒
int second = c1.get(Calendar.SECOND);
// 获得星期几(注意(这个与Date类是不同的):1代表星期日、2代表星期1、3代表星期二,以此类推)
int day = c1.get(Calendar.DAY_OF_WEEK);

Calendar类实现了公历日历,GregorianCalendar是Calendar类的一个具体实现。其构造方法。

GregorianCalendar():在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。
GregorianCalendar(int year, int month, int date):在具有默认语言环境的默认时区内构造一个带有给定日期设置的 GregorianCalendar
GregorianCalendar(int year, int month, int date, int hour, int minute):为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。
GregorianCalendar(int year, int month, int date, int hour, int minute, int second):  为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。
GregorianCalendar(Locale aLocale):在具有给定语言环境的默认时区内构造一个基于当前时间的 GregorianCalendar。
GregorianCalendar(TimeZone zone):在具有默认语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。
GregorianCalendar(TimeZone zone, Locale aLocale): 在具有给定语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。

Calendar类的API:

void add(int field, int amount):根据日历规则,将指定的(有符号的)时间量添加到给定的日历字段中。
protected void computeFields():转换UTC毫秒值为时间域值
protected void computeTime():覆盖Calendar ,转换时间域值为UTC毫秒值
boolean equals(Object obj):比较此 GregorianCalendar 与指定的 Object。
int get(int field):获取指定字段的时间值
int getActualMaximum(int field):返回当前日期,给定字段的最大值
int getActualMinimum(int field):返回当前日期,给定字段的最小值
int getGreatestMinimum(int field): 返回此 GregorianCalendar 实例给定日历字段的最高的最小值。
Date getGregorianChange():获得格里高利历的更改日期。
int getLeastMaximum(int field):返回此 GregorianCalendar 实例给定日历字段的最低的最大值
int getMaximum(int field):返回此 GregorianCalendar 实例的给定日历字段的最大值。
Date getTime():获取日历当前时间。
long getTimeInMillis():获取用长整型表示的日历的当前时间
TimeZone getTimeZone():获取时区。
int getMinimum(int field):返回给定字段的最小值。
int hashCode():重写hashCode.
boolean isLeapYear(int year):确定给定的年份是否为闰年。
void roll(int field, boolean up):在给定的时间字段上添加或减去(上/下)单个时间单元,不更改更大的字段。
void set(int field, int value):用给定的值设置时间字段。
void set(int year, int month, int date):设置年、月、日的值。
void set(int year, int month, int date, int hour, int minute):设置年、月、日、小时、分钟的值。
void set(int year, int month, int date, int hour, int minute, int second):设置年、月、日、小时、分钟、秒的值。
void setGregorianChange(Date date):设置 GregorianCalendar 的更改日期。
void setTime(Date date):用给定的日期设置Calendar的当前时间。
void setTimeInMillis(long millis):用给定的long型毫秒数设置Calendar的当前时间。
void setTimeZone(TimeZone value):用给定时区值设置当前时区。
String toString():返回代表日历的字符串。

4.Time :JDK8 新时间类

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public class TimeDemo {
    public static void main(String[] args) {
        //1------获取系统时间---------
        // 当前精确时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前精确时间:" + now); //2021-05-30T13:28:19.967
        // 获取当前日期
        LocalDate localDate = LocalDate.now();
        System.out.println("当前日期:" + localDate); //2021-05-30
        // 获取当天时间
        LocalTime localTime = LocalTime.now();
        System.out.println("当天时间:" + localTime); //13:28:19.968
        // 有时区的当前精确时间
        ZonedDateTime nowZone = LocalDateTime.now().atZone(ZoneId.systemDefault());
        System.out.println("当前精确时间(有时区):" + nowZone);//2021-05-30T13:28:19.968+08:00[Asia/Shanghai]

        //2------构造时间---------
        LocalDateTime ofTime = LocalDateTime.of(2019, 10, 1, 8, 8, 8);
        System.out.println("当前精确时间:" + ofTime);
        LocalDate localDate1 = LocalDate.of(2019, 10, 01);
        System.out.println("当前日期:" + localDate1);
        LocalTime localTime1 = LocalTime.of(12, 01, 01);
        System.out.println("当天时间:" + localTime1);

        //3------时间转换---------
        // 字符串转LocalDateTime
        LocalDateTime parseTime = LocalDateTime.parse("2019-10-01T22:22:22.222");
        System.out.println("字符串时间转换:" + parseTime);
        // 字符串转LocalDate
        LocalDate formatted = LocalDate.parse("20190101", DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("字符串日期转换-指定格式:" + formatted);
        // Date 转换成 LocalDateTime
        Date date = new Date();
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println("Date 转换成 LocalDateTime:" + LocalDateTime.ofInstant(date.toInstant(), zoneId));
        // LocalDateTime 转换成 Date
        LocalDateTime localDateTime = LocalDateTime.now();
        Date toDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println("LocalDateTime 转换成 Date:" + toDate);
        // 当前时间转时间戳
        long epochMilli = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println("当前时间转时间戳:" + epochMilli);
        // 时间戳转换成时间
        LocalDateTime epochMilliTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneId.systemDefault());
        System.out.println("时间戳转换成时间:" + epochMilliTime);

        //4------时间格式化---------
        LocalDateTime now1 = LocalDateTime.now();
        System.out.println("当前时间:" + now1);
        System.out.println("格式化后:" + now1.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        System.out.println("格式化后:" + now1.format(DateTimeFormatter.ISO_LOCAL_DATE));
        System.out.println("格式化后:" + now1.format(DateTimeFormatter.ISO_LOCAL_TIME));
        System.out.println("格式化后:" + now1.format(DateTimeFormatter.ofPattern("YYYY-MM-dd hh:mm:ss")));

        //5------时间比较---------
        LocalDateTime now2 = LocalDateTime.now();
        LocalDateTime yestory = now2.minusDays(1);
        System.out.println(now2 + "在" + yestory + "之后吗?" + now2.isAfter(yestory));
        System.out.println(now2 + "在" + yestory + "之前吗?" + now2.isBefore(yestory));
        // 时间差
        long day = yestory.until(now2, ChronoUnit.DAYS);
        long month = yestory.until(now2, ChronoUnit.MONTHS);
        long hours = yestory.until(now2, ChronoUnit.HOURS);
        long minutes = yestory.until(now2, ChronoUnit.MINUTES);
        long seconds = yestory.until(now2, ChronoUnit.SECONDS);
        System.out.println("相差月份" + month+"相差天数" + day+"相差小时" + hours+"相差分钟" + minutes+"相差秒" + seconds);

        //5------时间加减---------
        LocalDateTime now3 = LocalDateTime.now();
        System.out.println("当前时间:"+now3);
        LocalDateTime plusTime = now3.plusMonths(1).plusDays(1).plusHours(1).plusMinutes(1).plusSeconds(1);
        System.out.println("增加1月1天1小时1分钟1秒时间后:" + plusTime);
        LocalDateTime minusTime = now3.minusMonths(2);
        System.out.println("减少2个月时间后:" + minusTime);
        
        //6------时间扩展---------
        LocalDateTime now4 = LocalDateTime.now();
        System.out.println("当前时间:" + now4);
        // 第一天
        LocalDateTime firstDay = now4.withDayOfMonth(1);
        System.out.println("本月第一天:" + firstDay);
        // 当天最后一秒
        LocalDateTime lastSecondOfDay = now4.withHour(23).withMinute(59).withSecond(59);
        System.out.println("当天最后一秒:" + lastSecondOfDay);
        // 最后一天
        LocalDateTime lastDay = now4.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("本月最后一天:" + lastDay);
        // 是否闰年
        System.out.println("今年是否闰年:" + Year.isLeap(now4.getYear()));
    }
}

5.System

system中包含了in、out和err三个成员变量,分别代表标准输入流(键盘输入)、标准输出流(显示器)和标准错误输出流(显示器)。

//标准输入流
public final static InputStream in;
//标准输出流
public final static PrintStream out;
//标准错误流
public final static PrintStream err;

常用API

System.arraycopy(a,b,c,d,e):   其中,a是被复制的数组,b是复制的起始位置,c是复制到的数组,d是复制到这个数组的起始位置,e是复制到这个数组的结束位置。
System.currentTimeMillis():返回毫秒数。
System.getProperties():获取系统属性。
System.gc():用来运行JVM中的垃圾回收器,完成内存中垃圾的清除。
System.exit(0):结束正在运行的Java程序。参数传入一个数字即可。通常传入0记为正常状态,其它为异常状态。

6.Scanner

创建 Scanner 对象的基本语法:

Scanner s = new Scanner(System.in);

实例:如果要输入 int 或 float 类型的数据,在 Scanner 类中也有支持,但是在输入之前最好先使用 hasNextXxx() 方法进行验证,再使用 nextXxx() 来读取。

import java.util.Scanner;
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
        int i = 0;
        float f = 0.0f;
        System.out.print("输入整数:");
        if (scan.hasNextInt()) {
            // 判断输入的是否是整数
            i = scan.nextInt();
            // 接收整数
            System.out.println("整数数据:" + i);
        } else {
            // 输入错误的信息
            System.out.println("输入的不是整数!");
        }
        System.out.print("输入小数:");
        if (scan.hasNextFloat()) {
            // 判断输入的是否是小数
            f = scan.nextFloat();
            // 接收小数
            System.out.println("小数数据:" + f);
        } else {
            // 输入错误的信息
            System.out.println("输入的不是小数!");
        }
        scan.close();
    }
}

next() 与 nextLine() 区别

next():

  • 一定要读取到有效字符后才可以结束输入。
  • 对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
  • 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
  • next() 不能得到带有空格的字符串。

nextLine():

  • 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
  • 可以获得空白。

7.Integer

   public void testEquals() {
        int int1 = 12;
        int int2 = 12;
        
        Integer integer1 = new Integer(12);
        Integer integer2 = new Integer(12);
        Integer integer3 = new Integer(127);
        
        Integer a1 = 127; //或者写成Integer a1 = Integer.valueOf(127);
        Integer a2 = 127;//或者写成Integer a2 = Integer.valueOf(127);
        
        Integer a = 128;
        Integer b = 128;
            
        System.out.println("int1 == int2 -> " + (int1 == int2));                    
        System.out.println("int1 == integer1 -> " + (int1 == integer1));            
        System.out.println("integer1 == integer2 -> " + (integer1 == integer2));    
        System.out.println("integer3 == a1 -> " + (integer3 == a1));                
        System.out.println("a1 == a2 -> " + (a1 == a2));                            
        System.out.println("a == b -> " + (a == b));                                                    
    }   

答案是:
1、 int1 == int2 -> true
2、 int1 == integer1 -> true
3、 integer1 == integer2 -> false
4、 integer3 == a1 -> false
5、 a1 == a2 -> true
6、 a == b -> false
分析:
1、int1 == int2 为true。
2、int1 == integer1,Integer是int的封装类,当Integer与int进行==比较时,Integer就会拆箱成一个int类型,所以还是相当于两个int类型进行比较,这里的Integer,不管是直接赋值,还是new创建的对象,只要跟int比较就会拆箱为int类型,所以就是相等的。
3、integer1 == integer2 -> false,这是两个都是对象类型
4、integer3 == a1 -> false , integer3是一个对象类型,而a1是一个常量它们存放内存的位置不一样,所以也不等。
5、6 看起来是一模一样的为什么一个是true,一个是false,这是因为Integer作为常量时,对于-128到127之间的数,会进行缓存,也就是说int a1 = 127时,在范围之内,这个时候就存放在缓存中,当再创建a2时,java发现缓存中存在127这个数了,就直接取出来赋值给a2,所以a1 == a2的。当超过范围就是new Integer()来new一个对象了,所以a、b都是new Integer(128)出来的变量,所以它们不等。

8.Optional

从 Java 8 引入的一个很有趣的特性是 Optional 类。Optional 类主要解决的问题是臭名昭著的空指针异常(NullPointerException)。

  • Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
  • Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
  • Optional 类的引入很好的解决空指针异常。
API
public class Java8Tester {
   public static void main(String args[]){
   
      Java8Tester java8Tester = new Java8Tester();
      Integer value1 = null;
      Integer value2 = new Integer(10);
        
      // Optional.ofNullable - 允许传递为 null 参数
      Optional<Integer> a = Optional.ofNullable(value1);
        
      // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
      Optional<Integer> b = Optional.of(value2);
      System.out.println(java8Tester.sum(a,b));
   }
    
   public Integer sum(Optional<Integer> a, Optional<Integer> b){
    
      // Optional.isPresent - 判断值是否存在
        
      System.out.println("第一个参数值存在: " + a.isPresent());
      System.out.println("第二个参数值存在: " + b.isPresent());
        
      // Optional.orElse - 如果值存在,返回它,否则返回默认值
      Integer value1 = a.orElse(new Integer(0));
        
      //Optional.get - 获取值,值需要存在
      Integer value2 = b.get();
      return value1 + value2;
   }
}
结果

9. 枚举类

枚举类出现前
枚举类出现后
枚举类出现前的有参实例化
枚举类出现后的有参实例化
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容