Java-常用类

2021/11/29 17:10:22

本文主要是介绍Java-常用类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java-常用类

包装类

//    Boolean --> boolean
//    Character --> char
//    Byte  --> byte
//    Integer --> int
//    Short --> short
//    Long --? long
//    Double --> double
//    Float --> float

Integer

  1. 基础类型和包装类之间的转换

public class IntegerType {

    public static void main(String[] args) {
        // 演示 int <--> Integer 的装箱和拆箱
        // jdk5 前是 手动装箱和拆箱
        // 手动装箱
        int n1 = 100;
        Integer integer = new Integer(n1); //  方法1
        Integer integer1 = Integer.valueOf(n1); // 方法2


        // 手动拆箱
        int i = integer.intValue();

        // 自动装箱
        int n2 = 200;
        Integer integer2 = n2; // 底层调用 Integer.valueOf()
        // 自动拆箱
        int n3 = integer2;  // 底层调用 integer.intValue()

    }

}
				Object object1 = true? new Integer(1) : new Double(2.0);
        System.out.println(object1);
        /*
            结果为 1.0
            解释为 精度为Double,三元运算法的精度为double
         */
        Object object2;
        if (true)
            object2 = new Integer(1);
        else
            object2 = new Double(2.0);
        System.out.println(object2);
        /*
            结果为 1
            分别计算
         */
  1. 包装类和包装类之间的转换

				// 包装类 Integer --> String
        Integer i = 100;
        // 方式1
        String str1 = i + "";
        // 方式2
        String str2 = i.toString();
        // 方式3
        String str3 = String.valueOf(i);

        // String --> Integer
        // 方式1
        String str4 = "12345";
        Integer integer = Integer.valueOf(str4);
        // 方式2 构造器
        Integer integer1 = new Integer(str4);
  1. 常用方法(边学边用)

				Integer i = new Integer(1);
        Integer j = new Integer(2);
        System.out.println(i == j); // false

        Integer m = 1; // 底层Integer.valueOf(1) --> 范围在-128 -- 127 之内 在缓存中直接返回值
        Integer n = 1; // 底层Integer.valueOf(1) --> 范围在-128 -- 127 之内 在缓存中直接返回值
        System.out.println(m == n); // true

        Integer x = 128; // 底层Integer.valueOf(1) --> 范围在-128 -- 127 之外 要创建一个对象
        Integer y = 128; // 底层Integer.valueOf(1) --> 范围在-128 -- 127 之外 要创建一个对象
        System.out.println(x == y); // false


 				/*
        public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
        }
        This method will always cache values in the range -128 to 127,
         */

String

  1. 结构剖析

				String name = "wxy"; // 字符串常量
        // 字符串中的字符和汉字都占两个 字节
        System.out.println();
        // 常用的四个构造器
//        String s1 = new String(String original);
//        String s2 = new String(char[] a);
//        String s3 = new String(char[] a, int startIndex, int count);
//        String s4 = new String(byte[] b);
        String s1 = new String("wxy");
        char[] a = {'w','x','y'};
        String s2 = new String(a);
        String s3 = new String(a, 0, 2);
        byte[] b = {1, 2, 3};
        String s4 = new String(b);
        // String类 实现了接口 Serializable 因此String可以串行化:可以在网络传输
        // String类 实现了Comarable 因此String对象可以进行比较
        // String 是 final类,不能被其他类继承

        // String中 有属性 private final char value[]; 用于存放字符串内容
        // value 是一个final 类型 ,不可修改,地址不可修改,不是内容不可修改   value --> D2565X  因此不可改变为value --> null获取其他
        final char[] value = {'a', 'b'};
        value[0] = 'c';
        System.out.println(value);
        char[] v2 = {'1', '2'};
        // value = v2;   ----- 错误
  1. 测试

				String s1 = "wxy";
        String s2 = new String("wxy");
        String s3 = "wxy";
        System.out.println(s1 == s2);  // 比较内存 s2直接指向堆,s1指向常量池
        System.out.println(s1.equals(s2)); // 比较值大小,equals方法中 直接取出 value进行比较
        // s1和s3都直接指向常量池
        System.out.println(s1 == s3); // s1没有wxy  创建一个wxy常量,因此s3的时候,不需在创建,可以直接指向常量wxy

        // intern 若常量池已经包含了此String的equals(Object),则返回池中的字符串
        // 否则,将此String对象添加到池中,并返回String对象的引用
        // 返回常量池的地址
        System.out.println(s1 == s2.intern());
        System.out.println(s2 == s1.intern());
        System.out.println(s2 == s2.intern());
				People p1 = new People();
        p1.name = "wxy";
        People p2 = new People();
        p2.name = "wxy";

        // 字符比较equals
        System.out.println(p1.name.equals(p2.name)); // True
        // p1 p2 指向的不同,但是属性name都指向常量池中的wxy,因此相同
        System.out.println(p1.name == p2.name); // true
        System.out.println(p1.name == "wxy"); // true

        String s1 = new String("abc");
        String s2 = new String("abc");
        // s1 s2 是两个对象,指向堆中的不同地址
        System.out.println(s1 == s2); // false
  1. 对象特性

		public static void main(String[] args) {

        // 以下创建了几个对象   ---  2
        String s1 = "hello";
        s1 = "hahah0";

        // 创建了几个对象  ---  1,  不是三个或两个,编译器会自动优化 创建一个  helloabc
        // 等价于  String s2 = "helloabc"  编译器会判断多余的常量是否有实际作用
        String s2 = "hello" + "abc";

        // 创建了几个对象

        String s3 = "hello";
        String s4 = "abc";
        // 1.先创建一个 StringBuilder sb = new StringBuilder();
        // 2.执行  sb.append("hello");
        // 3.执行  sb.append("abc");
        // 4.sb.toString();
        // 最后,其实是 s5 指向堆中的对象(String) value[] --> 池中 "helloabc"
        // s5 先创建了一个对象 指向堆 然后再指向常量池中
        String s5 = s3 + s4;
        // 验证:
        String s6 = "helloabc";
        System.out.println(s5 == s6); // false
        // 规则: 1.常量相加看常量池  2.变量相加看堆
        System.out.println(s2 == s6); // true

    }
public class StringType04 {
        String str = new String("wxy");
        final char[] ch = {'j', 'a', 'v', 'a'};
        private void charge(String str, char[] ch) {
            str = "java";
            ch[0] = 'h';
        }
    public static void main(String[] args) {
        StringType04 test1 = new StringType04();
        test1.charge(test1.str, test1.ch);
        System.out.println(test1.str); // wxy
        System.out.println(test1.ch); // hava
    }
}

  1. 常用方法

    1. 其他参考手册
public class StringFunction {
    /*
    常用方法 1:
    1. equals -- 区分大小写,判断是否相等
    2. equalslgnoreCase -- 或缺大小写的判断内容是否相等
    3. length -- 获取字符的个数,字符串的长度
    4. indexOf -- 获取字符在字符串中第一次出现的索引
    5. lastIndexOf -- 获取字符在字符串中最后一次出现的索引
    6. substring -- 获取start 到 end 的子串
    7. trim  --  去除前后空格
    8. charAt  --  获取index的字符
     */
    /*
    常用方法 2:
    1. toUpperCase -- 转换为全大写字符串
    2. toLowerCase -- 转换为全小写字符串
    3. concat -- 拼接字符串
    4. replace  --  替换, 将字符串中的str1全部替换成str2  返回的结果才是替换完的结果 需要接收
    5. split  -- 分割 ,以什么字符进行分割,且返回为一个String[],
    6. compareTo  -- 比较两个字符串大小,如果前者大,返回整数,如果后者大,返回负数,如果相等,返回0
                   // 先挨个比较,当不同时,返回前-后的值; 若其长度不同,且其短的前几个都与长的相同,就是长的包含短的,
                   // 直接返回前者的长度-后者的长度。
    7. toCharArray -- 转换字符数组
    8. format -- 格式化,看info示例
     */
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "Hello";
        String s3 = "as das wad  ";
        String s4 = "asdasdasd,asdasdasd,dasdasdasd,asdasdasd";
        // 常用方法 1
        System.out.println(s1.equals(s2));
        System.out.println(s1.equalsIgnoreCase(s2));
        System.out.println(s1.length());
        System.out.println(s1.indexOf('e'));
        System.out.println(s1.indexOf("ll"));
        System.out.println(s1.lastIndexOf('e'));
        System.out.println(s1.substring(2));
        System.out.println(s1.substring(1, 3));
        System.out.println(s3.trim());
        System.out.println(s1.charAt(3));
        // 常用方法 2
        System.out.println(s1.toUpperCase());
        System.out.println(s2.toLowerCase());
        System.out.println(s1.concat(s2).concat(" and wxy"));
        System.out.println(s1.replace("ll", "ww"));
        String[] strs = s4.split(",");  // regex正则表达式,特殊字符需要转义符
        for (String str : strs) {
            System.out.println(str);
        }
        char[] str2 = s3.toCharArray();
        for (char ch: str2) {
            System.out.println(ch);
        }
        System.out.println(s1.compareTo(s2));
        System.out.println(s1.compareTo(s1));
        System.out.println(s3.compareTo(s4));

        // 格式化
        String name = "wxy";
        int age = 10;
        double score = 98.566;
        String formatstr = "姓名:%s  年龄:%d  成绩:%.2f"; // 四舍五入
        /*
        占位符: %s--字符串   %d--整数   %.2f--保存两位的小数   %c--char类型
        这些占位符由后面变量来替换
         */
        String info = String.format(formatstr, name, age, score);
        System.out.println(info);

    }
}

StringBuffer

  1. StringBuffer代表可变的字符序列,可对字符串内容进行增删,可变长度
  2. StringBuffer是一个容器
public class StringBuffer01 {
    public static void main(String[] args) {
        // 1.StringBuffer的字节父类 是 AbstractStringBuffer
        // 2.StringBuffer 实现了Serializable  即 StringBuffer可以序列化
        // 3.父类中AbstractStringBuffer 有属性 char[] value ,
        // 不是final  --- 相对于 String 的final常量 不方便,因此更新的效率更好
        // String需要每次都更新地址,而StringBuffer一般是更新内容
        // 该 value 数组 存放 字符串内容,  引出 --  存放在堆中
        // 4.StringBuffer 是一个final类, 不可被继承
        // 5.因为StringBuffer 字符内容存在于char[] value,所有的更新不用每次都更新地址(即创新对象)
        StringBuilder stringBuilder = new StringBuilder("hello world java");
        System.out.println(stringBuilder);
        // 构造器的应用
        // 1.构造器的使用  默认16位
        StringBuilder sb1 = new StringBuilder();
        // 2.通过构造器指定char[] 大小
        StringBuilder sb2 = new StringBuilder(100);
        // 3.通过 给一个String 创建 StringBuffer   capacity = sb.length+16
        StringBuilder sb3 = new StringBuilder("wxy");

        // String和StirngBuffer之间的转换
        // 1. String --> StringBuffer
        //  1.1 构造器   注意: 返回的是一个StringBuffer对象,不会改变s1
        String s1 = "java";
        StringBuilder sbs = new StringBuilder(s1);
        //  1.2 append方法添加
        StringBuilder sbs1 = new StringBuilder();
        StringBuilder sbs2 = sbs1.append(s1);

        // 2. StringBuffer --> String
        //  2.1 使用toString()方法
        StringBuilder sbs3 = new StringBuilder("asdasdasd");
        String s2 = sbs3.toString();
        //  2.2 使用构造
        String s3 = new String(sbs3);

    }
}

  1. 常用方法–增删改查
public class StringBufferfunction {
    public static void main(String[] args) {
        /*
        StringBuffer接入方法
        1. append() 参数可以是int String boolean double等
         */
        StringBuffer sb1 = new StringBuffer("java");
        sb1.append(" hello ");
        sb1.append(111).append(true).append(10.3);
        System.out.println(sb1);
        /*
        StringBuffer删除方法
        1. delete( start , end )
        2. deleteCharAt(index)  删除指定下标的元素
         */
        sb1.delete(10,15);
        System.out.println(sb1);
        sb1.deleteCharAt(1);
        System.out.println(sb1);
        /*
        StringBuffer修改方法
        1.replace(start, end, str);
         */
        sb1.replace(1,4, "wxy");
        System.out.println(sb1);
        /*
        StringBuffer查找方法
        1.indexOf(str);
         */
        System.out.println(sb1.indexOf("he"));
        /*
        StringBuffer插入方法
        1.insert(offset, xxx);  在offset的位置插入元素xxx,其他元素后移
        其中xxx可以是int double String 等
         */
        sb1.insert(10, "xxxxxx");
        System.out.println(sb1);
    }
}
  1. 测试
public class StringBufferTest {
    public static void main(String[] args) {
        // first test
        String s = null;
//        StringBuffer sb = new StringBuffer(s); // 有问题 因为str.length() 存在错误
        StringBuffer sb = new StringBuffer();
        sb.append(s);  // 被转换为字符串null
        System.out.println(sb.length());

        // second test  价格表示:123,123.45
        /*
        1. 定义Scanner 队形,接收用户的输入
        2. 希望使用StringBuffer的insert,所需要将String转换成StringBuffer
        3. 然后使用相关方法进行字符串处理
        例如 :123123123123.123 --> 123,123,123,123.123
         */
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        StringBuffer sbs = new StringBuffer(str);
        int index = sbs.indexOf(".");
        for (int i = index-3; i > 0; i -= 3) {
            sbs.insert(i, ",");
        }
        System.out.println(sbs);
    }
}

StringBuilder

/*
    1. StringBuilder也是一个可变的序列,此类提供一个与StringBuffer兼容的API,
    但不保证同步(StringBuilder不是线程安全的,存在多线程)。此类被设计用作
    StringBuffer的一个简易替换,用在字符串缓冲区被单个线程使用的时候,
    如果可能,建议优先采用此类,因为大多数实现中,它比StringBuffer要快
    2. 在StringBuilder上的主要操作是append和insert方法,
     可重载这些方法,以接受任意类型的数据
    3. StringBuilder 继承 AbstractStringBuilder 类
    4. 实现了 Serializable ,说明 其对象 也可 串行化-可以进行网络传输,可以保存文件
    5. StringBuilder 对象字符序列仍然是存放在其父类 AbstractStringBuilder中,因此字符序列也在堆中
    6. StringBuilder 是final类, 不可被继承
    7. StringBuilder 的方法,没有做同步或互斥的处理 即 没有关键字synchronized
        因此在单线程中使用StringBuilder
     */

三者比较和结论

  1. 比较
    /*
    String StringBuffer StringBuilder 比较
    1. StringBuilder 和 StringBuffer 非常类似,均戴白可变的序列,而且方法也一样
    2. String: 不可变序列,效率低,但是复用率高--常量不需要重复创建对象
    3. StringBuffer 可变字符序列、效率高、线程安全
    4. StringBuilder  可变字符序列、效率最高、线程不安全
    5. String使用主要说明:
        String s ="a";   创建一个字符串
        s += b; 实际上原来的"a"字符串对象已经丢弃,现在又产生一个字符串s+"b" = "ab"。
        如果多次执行这些改变串内容的操作,会导致大量副本字符串对象存留在内存中,降低效率。
        如果这样的操作放在循环中,会极大影响程序的性能。
        结论:如果对String做大量修改,不建议使用String
     6. 效率: StringBuilder > StringBuffer > String
     */
  1. 结论
		/*
    结论
    1. 如果字符串存在大量的修改操作,一般使用StringBuilder 或StringBuffer
    2. 如果字符串存在大量的修改操作,并在单线程的情况下,使用StringBuilder
    3. 如果字符串存在大量的修改操作,并在多线程的情况下,使用StringBuffer
    4. 如果字符串存在少量的修改操作,被多个对象引用,使用String。比如配置信息等
     */

Math类

		// Math常用方法
        // 1. abs()取绝对值 参数可以是 int long float double
        System.out.println(Math.abs(-9.5));
        // 2. pow()求幂  两个参数均为double
        System.out.println(Math.pow(1, 2.1));
        // 3. ceil() 向上取整, 默认是可以向上取整的
        System.out.println(Math.ceil(-13.3));
        // 4. floor() 向下取整
        System.out.println(Math.floor(-12.3));
        // 5. round() 四舍五入
        System.out.println(Math.round(12.6));
        // 6. sqrt() 开方
        System.out.println(Math.sqrt(16));
        // 7. min() 取两者最小值  取高精度
        System.out.println(Math.min(11.2, 123));
        // 8. max() 去两者的最大值  若有double则返回double,若无double有float则返回float
        System.out.println(Math.max(11.2, 123));
        // 9. random() 取随机数, 默认区间是[0,1)
        for (int i = 0; i < 10; i++) {
            System.out.print((int) (Math.random() * 7) + 1 + " "); // [2,8)
        }// Math常用方法
        // 1. abs()取绝对值 参数可以是 int long float double
        System.out.println(Math.abs(-9.5));
        // 2. pow()求幂  两个参数均为double
        System.out.println(Math.pow(1, 2.1));
        // 3. ceil() 向上取整, 默认是可以向上取整的
        System.out.println(Math.ceil(-13.3));
        // 4. floor() 向下取整
        System.out.println(Math.floor(-12.3));
        // 5. round() 四舍五入
        System.out.println(Math.round(12.6));
        // 6. sqrt() 开方
        System.out.println(Math.sqrt(16));
        // 7. min() 取两者最小值  取高精度
        System.out.println(Math.min(11.2, 123));
        // 8. max() 去两者的最大值  若有double则返回double,若无double有float则返回float
        System.out.println(Math.max(11.2, 123));
        // 9. random() 取随机数, 默认区间是[0,1)
        for (int i = 0; i < 10; i++) {
            System.out.print((int) (Math.random() * 7) + 1 + " "); // [2,8)
        }

Arrays类

toString()

				Integer[] integers = {1, 3, 8, 5, 2, 2};
        // 1. toString()  返回一个字符串
        System.out.println(Arrays.toString(integers));

sort()

				// 2. sort() 可以只有一个数组参数 , 也可以是说三个  数组,fromIndex,toIndex,  采用二叉排序
        Arrays.sort(integers);
        System.out.println(Arrays.toString(integers));
        // 排序规则  实现了 Comparator接口,需要实现compare的方法
        // 实现Comparator接口的匿名内部类,实现compare方法  实现了逆序
        // sort() -- TimSort.sort() -- binarySort() -- binarySort() -- compare
        // 体现接口和动态类的好处
        Arrays.sort(integers, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                return i2 - i1;
            }
        });

其他方法

				// 3. binarySearch - 数组有序的二分查找  参数可以是int char double 数组
        // 要求该数组是有序的,如果该数组是无需的,不能使用binarySearch
        // 如果数组中不存在该元素,就返回 return -(low + 1);  可用于插入
        Integer[] arr = {1, 2, 3, 5, 8, 22};
        System.out.println(Arrays.binarySearch(arr, 33));
        // 4. copuOf() 数组元素的复制
        // 拷贝arr 中的 这么长的arr.length 的数据 给 arr1
        // 如果拷贝的长度 > arr.length 就在新数组的后面 增加 null  拷贝长度必须大于等于0
        Integer[] arr1 = Arrays.copyOf(arr, arr.length);
        Integer[] arr2 = Arrays.copyOf(arr, arr.length + 1);
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
        // 5. fill(数组参数, 值) 数组填充,   使用值替换数组中所有值
        Integer[] arr3 = {1, 9 ,3 , 2};
        Arrays.fill(arr3 , 5);
        System.out.println(Arrays.toString(arr3));
        // 6. equals() 比较两个数组是否一致
        System.out.println(Arrays.equals(arr2, arr3));
        System.out.println(Arrays.equals(arr, arr));
        // 7. aslist() 将数组或一组数转化为list
        List<Integer> list1 = Arrays.asList(arr2);
        List<Integer> list2 = Arrays.asList(1, 3, 5, 6);
        System.out.println(list1);
        System.out.println(list2);

测试(重点

public class Book {
    String name;
    double price;

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
    public Book() {
    }
    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }
}

public class Test {
    public static void main(String[] args) {
        Book book1 = new Book("红楼梦", 100);
        Book book2 = new Book("西游记", 222);
        Book book3 = new Book("三国演义", 111);
        Book book4 = new Book("水浒传新版", 333);
        Book[] books = new Book[4];
        books[0] = book1;
        books[1] = book2;
        books[2] = book3;
        books[3] = book4;
        // 1. 按price从大到小排序
        Arrays.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                if (o1.price - o2.price > 0)
                    return -1;
                else
                    return 1;
            }
        });
        for (Book book : books) {
            System.out.println(book);
        }
        System.out.println("------------------------------------");
        // 2. 按price从小到大排序
        Arrays.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                if (o1.price - o2.price > 0)
                    return 1;
                else
                    return -1;
            }
        });
        for (Book book : books) {
            System.out.println(book);
        }
        System.out.println("------------------------------------");
        // 4. 按name从小到大排序
        Arrays.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                if (o1.name.compareTo(o2.name) > 0)
                    return 1;
                else
                    return -1;
            }
        });
        for (Book book : books) {
            System.out.println(book);
        }
        System.out.println("------------------------------------");
        // 3. 按name长度从小到大排序
        Arrays.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                if (o1.name.length() - o2.name.length() > 0)
                    return 1;
                else
                    return -1;
            }
        });
        for (Book book : books) {
            System.out.println(book);
        }
    }
}

System类

public class SystemFunction {
    public static void main(String[] args) {
        // 1. arraycopy() 复制数组元素,比较适合底层调用 -- 看源码
        // 一般使用Arrays.copyOf 完成复制数组
        // 第一个参数 -源数组; 第二个参数 -开始拷贝的索引下标; 第三个参数 -目标数组;
        // 第四个参数 -把源数组拷贝到目标数组的索引位置; 第五个参数 -要拷贝的数据个数
        int[] a = {1,2,3};
        int[] d = new int[5];
        System.arraycopy(a, 0, d, 1, a.length);
        System.out.println(Arrays.toString(d));  // 0 1 2 3 0
        // 2. currentTimeMillis()  当前时间与1970.1.1 之间的时间差 毫秒级
        System.out.println(System.currentTimeMillis());
        // 3. gc() 运行垃圾回收机制
        System.gc();
        // 4. exit 退出当前程序
        System.out.println("ok1");
        // exit(0) 表示程序退出  0表示一个状态,正常状态
        System.exit(0);
        System.out.println("ok2");
    }
}

BigInteger和BigDecimal类

BigInteger

public class BigIntegerFunction {
    public static void main(String[] args) {
        // 保存精度更好的整数
        BigInteger big1 = new BigInteger("12312124124134234234123123123");
        System.out.println(big1);
        // 加减乘数
        BigInteger big2 = new BigInteger("1231231231231231235435");
        System.out.println(big1.add(big2));
        System.out.println(big1.subtract(big2));
        System.out.println(big1.multiply(big2));
        System.out.println(big1.divide(big2));
    }
}

BigDecimal

public class BigDecimalFunction {
    public static void main(String[] args) {
        // 保存精度更高的浮点数
        BigDecimal big1 = new BigDecimal("123123.123123123123123123123123");
        BigDecimal big2 = new BigDecimal("1.11113123");
        System.out.println(big1);
        System.out.println(big2);
        // 加减乘数
        System.out.println(big1.add(big2));
        System.out.println(big1.subtract(big2));
        System.out.println(big1.multiply(big2));
        System.out.println(big1.divide(big2, BigDecimal.ROUND_CEILING)); // 可能会出现循环异常ArithmeticException
        // 再调用divide方法时,可指定精度 BigDecimal.ROUND_CEILING
        // 如果有无限循环小数,就会保留 分子的 精度
    }
}

日期类

Date-一般

		public static void main(String[] args) throws ParseException {
        // 1. 空构造器-获取当前时间
        // 2. 默认的日期格式是国外的方式,因此同城需要对格式进行转换
        Date date1 = new Date();
        System.out.println(date1);
        // 1. long 构造器,表示毫秒数,计算时间 起始时间是1970-1-1 一般不使用
        Date date2 = new Date(23123);
        System.out.println(date2);
        // 1. 创建 SimpleDateFormat对象,可以指定相应的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss E");
        String format = sdf.format(date1);
        System.out.println(format);
        // 2. 字符串换为Date格式
        // 抛异常
        String date = "2021-11-11 12:11:33 星期三";
        Date date3 = sdf.parse(date);
        System.out.println(date3); // 会自动更新星期几
        System.out.println(sdf.format(date3));
    }

Calendar-不用

		public static void main(String[] args) {
        // Calender类是一个抽象类, 它为特点瞬间与一组 YEAR MONTH DAY_OF_MONTH HOUR等
        // 日期字段之间的转换提过一些方法,并为操作日历字段提供一些方法
        // 构造器是私有的, private, 可以通过getInstance() 来获取实例
        Calendar calendar = Calendar.getInstance(); // new不了
        System.out.println(calendar); // 有很多字段在其中
        // 获取日历对象的某个日历字段
        System.out.println("年-" + calendar.get(Calendar.YEAR));
        System.out.println("月-" + (calendar.get(Calendar.MONTH) + 1));
        System.out.println("日-" + calendar.get(Calendar.DAY_OF_MONTH));
        System.out.println("小时-" + calendar.get(Calendar.HOUR_OF_DAY));
        System.out.println("分钟-" + calendar.get(Calendar.MINUTE));
        System.out.println("秒-" + calendar.get(Calendar.SECOND));
        // Calendar 没有专门的格式化的方法,需要进行DIY组合
     	  // HOUR_OF_DAY -24进制
        System.out.println(calendar.get(Calendar.YEAR) + "-" +
                (calendar.get(Calendar.MONTH) + 1) + "-" +
                calendar.get(Calendar.DAY_OF_MONTH));
    }

				/*
        存在的问题:
        1. 可变性:像日期和时间这样的类是不可变的
        2. 偏移行:Date中的年份是从1900年开始,月份从0开始 计算时间是从1970年开始的
        3. 格式化:格式化只对Date有用,Calendar不行
        4. Date和Calendar 都不是线程安全的;不能处理闰秒等(每隔2天,多出1s)无法准确表示闰年
         */

LocalDate-推荐

 		public static void main(String[] args) {
        // 1. LocalDate-日期 LocalTime -时间 LocalDateTime -日期时间  JDK8加入
        // 2. LocalDate 只包含日期,可获取日期 年月日
        // LocalTime 只包含时间,可获取时间 时分秒
        // LocalDateTime 包含日期+时间,可获得日期和时间 年月日时分秒
        // 1,获取当前时间
        LocalDateTime ldt = LocalDateTime.now(); // LocalDate.now()  LocalTime.now()
        System.out.println(ldt);
        System.out.println(ldt.getYear());
        System.out.println(ldt.getMonth()); // 英文月份
        System.out.println(ldt.getMonthValue()); // 数值月份
        System.out.println(ldt.getDayOfMonth());
        System.out.println(ldt.getHour());
        System.out.println(ldt.getMinute());
        System.out.println(ldt.getSecond());
        // ----------------------格式化---------------------------------
        // 使用DateTimeFormatter对象
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dtf.format(ldt);
        System.out.println(format);
        // ----------------------时间戳---------------------------------
        // 转换Instant --> Date
        // 1. 通过静态方法 now() 获取当前时间戳对象
        Instant instant = Instant.now();
        System.out.println(instant);
        // 2. 通过 from 可以把 Instant 转换为 Date
        Date date = Date.from(instant);
        System.out.println(date);
        // 3. 通过 Date.toInstance() 可以吧date 转换为 Instant对象
        Instant in = date.toInstant();
        System.out.println(in);
        // ----------------------其他内容---------------------------------
        /*
        1. MontnDay类 检测重复事件
        2. 是否是闰年
        3. 使用plus或其他方法测试增加减少时间的某个部分 使用minus方法测试查看一年和一年后的日期
        等
         */
        LocalDateTime dateTime1 = ldt.plusDays(890);
        System.out.println(dateTime1);
        System.out.println(dtf.format(dateTime1));
        LocalDateTime dateTime2 = ldt.minusYears(2);
        System.out.println(dtf.format(dateTime2));
    }

测试

Homework1

javapublic class HomeWork1 {
    public static void main(String[] args) {
        String str = "asdbce";
        String s = reverse(str, 1, 5);
        System.out.println(s);
    }
    public static String reverse(String str, int start, int end) {
        char[] chs = str.toCharArray();
        for (int i = start, j = end; i < j; i++, j--) {
            if (chs[i] != chs[j]){
                char ch = chs[i];
                chs[i] = chs[j];
                chs[j] = ch;
            }
        }
        return new String(chs);
    }
}

Homework2

public class HomeWork2 {
    public static void main(String[] args) {
        String name = "wxy";
        String pwd = "123123";
        String email = "123123@qq.com";
        try {
            userRegister(name, pwd, email);
            System.out.println("注册成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    public static void userRegister(String name, String pwd, String email) {
        if (!(name.length() >= 2 && name.length() <= 4)) {
            throw new RuntimeException("用户名长度为2-4");
        }
        if (!(pwd.length() == 6 && isDigital(pwd))) {
            throw new RuntimeException("密码长度为6,且纯数字");
        }
        int i = email.indexOf("@");
        int j = email.indexOf(".");
        if (!(i < j && i > 0)){
            throw new RuntimeException("@应在.前");
        }
    }
    public static boolean isDigital(String str) {
        char[] chs = str.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            if (chs[i] < '0' || chs[i] > '9')
                return false;
        }
        return true;
    }
}

Homework3

public class HomeWork3 {
    public static void main(String[] args) {
        String name = "WWW xXX YYY";
        printName(name); // YYY,WWW .X
    }
    public static void printName(String str) {
        if (str == null) {
            System.out.println("姓名 不能为空");
            return;
        }
        String[] names = str.split(" ");
        if (names.length != 3){
            System.out.println("姓名格式不正确 XXX XXX XXX");
            return;
        }
        String format = String.format("%s,%s .%c", names[2], names[0], names[1].toUpperCase().charAt(0));
        System.out.println(format);

    }
}

Homework4

public class Homework4 {
    public static void main(String[] args) {
        String str = "123sasjczknSASDASZ123.+-Z";
        countString(str);
    }
    public static void countString(String str) {
        if (str == null) {
            System.out.println("不能是null");
            return ;
        }
        int numCount = 0;
        int lowerCount = 0;
        int upperCount = 0;
        int otherCount = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                numCount ++;
            } else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
                lowerCount ++;
            } else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
                upperCount ++;
            } else otherCount ++;
        }
        System.out.println(numCount + "数字");
        System.out.println(lowerCount + "小写字母");
        System.out.println(upperCount + "大写字母");
        System.out.println(otherCount + "其他字符");
    }
}


这篇关于Java-常用类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程