Java学习(10) —— 常用类

目录

一.  Object类

二.  包装类

三.  String类

    1. String类的内存分析

    2. String类中的常用方法

    3. String类与其他结构的转换

四.  StringBuffer类和StringBuilder类

五.  关于时间的类

       1. Date类

       2. SimpleDateFormat类

       3. Calendar类

       4. LocalDate类、LocalTime类、LocalDateTime类

       5. Instant类

六.  Java比较器

       1. Comparable接口(自然排序)

       2. Comparator(定制排序)

七.  System类

八.  Math类


一.  Object类

     (1)Object类是所有Java类的根父类;

     (2)如果在类的声明中未使用extends关键字指明其父类,则默认为java.lang.Object类;

     (3)Object类中只声明了一个空参构造器;

     (4) Object类中的方法具有通用性,方法有:equals() 、toString() 、getClass()、hashCode()、clone()、finalize() 等等

        equals()

        == :是运算符,可以用在基本数据类型变量和引用数据类型变量中;如果比较的是基本数据变量,比较的是两个变量保存的数据是否相等(不一定要类型相同),如果比较的是引用数据类型变量,比较两个对象的地址是否相同,即两个引用是否指向的同一个对象实体。

       equals():(1)是一个方法,只能用于引用数据类型;(2)Object类中定义的equals()方法和==作用相同;(3)像String、Date、File、包装类等都重写了Object中的equals()方法,重写以后比较的是两个对象实体内容是否相等。

public class Test{
    public static void main(String[] args) {
        // ==
        //(1)基本数据类型
        int i1 = 5;
        int i2 = 5;
        System.out.println(i1 == i2); //true
        double i3 = 5.0;
        System.out.println(i1 == i3); //true

        //(2)引用数据类型
        Data data1 = new Data(1,2);
        Data data2 = new Data(1,2);
        System.out.println(data1 == data2); //false


        //equals()
        System.out.println(data1.equals(data2)); //false

        String str1 = new String("Tom");
        String str2 = new String("Tom");
        System.out.println(str1.equals(str2)); //true
    }
}


class Data{
    int m;
    int n;
    public Data(){

    }
    public Data(int m, int n){
        this.m = m;
        this.n = n;
    }

}

        toString()

      (1)Object类中定义的toString()返回对象的地址;(2)像String、Data、File、包装类等都重写了Object中的toString()方法,使得在调用对象的toString()时,返回实体内容信息。

public class Test{
    public static void main(String[] args) {

        Data data = new Data(1,2);

        System.out.println(data.toString()); //Data@776ec8df

        String str = new String("Tom");
        System.out.println(str.toString()); //Tom
    }
}


class Data{
    int m;
    int n;
    public Data(){

    }
    public Data(int m, int n){
        this.m = m;
        this.n = n;
    }

}

二.  包装类

       8种基本数据类型对应的包装类有:Byte、Short、Integer、Long、Float、Double、Boolean、Character;使得基本数据类型的变量具有类的特征。

public class Test{
    public static void main(String[] args) {
        //基本数据类型 转到 包装类:自动装箱
        int i = 13;
        Integer in1 = i;
        System.out.println(in1.toString());     // 13    //使得基本数据类型具有了类的特征
        System.out.println(in1);                //13


        Double d2 = 13.12;
        System.out.println(d2.toString());     // 13.12
        System.out.println(d2);                //13.12

        //包装类 转到 基本数据类型 :自动拆箱
        int i1 = in1;       //i1 为基本数据类型,不具有类的特征


        //基本数据类型、包装类 转到 String类型 : 调用String里重载的valueOf()
        int i2 = 12;
        String str1 = String.valueOf(i2);   //str1为String类型
        System.out.println(str1);

        Integer i3 = 12;
        String str2 = String.valueOf(i3);  //str2为String类型
        System.out.println(str2);

        //String类型 转到 基本数据类型、包装类 : 调用包装类的parseXxx()
        String str4 = "123";
        int i4 = Integer.parseInt(str4);

        String str = "true";
        boolean b = Boolean.parseBoolean(str);
    }
}

三.  String类

      1. String类的内存分析

        (1)String是字符串,用 "  " 表示;

        (2)String内部用数组来存储字符串数据,数组声明为 final char[ ] value,由于数组被声明为final,因此不可以被继承。且数组不可以被修改,是不可变的。

       (3)String代表不可变的字符序列,具有不可变性。字符串常量池中不会存储相同内容的字符串。具体体现为:①当对字符串变量重新赋值时,相当于重新指定新的内存区域进行赋值,不是修改了原本内存处的值,原本内存处的值依然存在,该变量指向新的内存地址;②当对现有的字符串进行连接操作时,也相当于重新指定新的内存区域进行赋值,新内存区域的值为两个字符串连接后的值;③当调用String方法的replace()方法修改指定的字符或字符串时,也相当于重新指定新的内存区域进行赋值。

public class Test{
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "xyz";
        String s3 = "abc";
        System.out.println(s1);         //abc
        System.out.println(s2);         //xyz
        System.out.println(s3);         //abc
        System.out.println(s1 == s3);   //true   比较的是s1和s3的地址值,s1和s3指向同一个地址,该地址的值为abc
        System.out.println(s1 == s2);   //false

        s1 = "def";
        System.out.println(s1);         //def
        System.out.println(s1 == s3);   //false  s1重新指向新的地址,该地址的值为def

        s2 = "abc";
        System.out.println(s2);         //abc
        System.out.println(s2 == s3);   //true   s2和s3指向同一个地址

        s2 += "mn";
        System.out.println(s2);         //abcmn
        System.out.println(s2 == s3);    //false  

        String s4 = "abc";
        System.out.println(s4 == s3);     //true
        String s5 = s4.replace("ab","st");
        System.out.println(s5);          //stc
        System.out.println(s5 == s3);    //false

        //此时常量池中有5个字符串:abc、xyz、def、abcmn、stc
    }
}

               String对象的创建:①String s1 = "hello";②String s1 = new String("hello"),

public class Test{
    public static void main(String[] args) {
        String s1 = "hello";      //s1存储的是方法区的常量池中hello的地址
        String s2 = "hello";

        String s3 = new String("hello");    //s3存储的是堆中char[]对应的地址,char[]对应的是常量池中的hello
        String s4 = new String("hello");

        System.out.println(s1 == s2);  //true
        System.out.println(s1 == s3);  //false
        System.out.println(s3 == s4);  //false

    }
}

               字符串连接:(1)两个字符串常量连接后的结果仍在常量池中;(2)一个变量和一个字符串常量连接后的结果在堆中;(3)如果连接后的结果调用intern()方法,结果在常量池中。

public class Test{
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "world";

        String s3 = "helloworld";
        String s4 = "hello" + "world";
        String s5 = s1 + "world";
        String s6 = "hello" + s2;
        String s7 = s1 + s2;

        System.out.println(s3 == s4);   //true
        System.out.println(s3 == s5);   //false
        System.out.println(s3 == s6);   //false
        System.out.println(s3 == s7);   //false
        System.out.println(s5 == s6);   //false
        System.out.println(s5 == s7);   //false


        String s8 = s5.intern();
        System.out.println(s3 == s8);   //true

    }
}

    2. String类中的常用方法:

      (1)length():返回字符串的长度;

      (2)charAt(int index):返回索引处的字符;

      (3)isEmpty():判断是否是空字符串;

      (4)toLowerCace():使用默认语言环境,将String中的所有字符转化为小写;

      (5)toUpperCace():使用默认语言环境,将String中的所有字符转化为大写;

      (6)trim():返回字符串的副本,忽略前空白和后空白;

      (7)equals(Object anObject):比较字符串的内容是否相同;

      (8)equalsIgnoreCase(String anotherString):忽略大小写,比较字符串的内容是否相同;

      (9)concat(String str):将指定字符串连接到此字符串的末尾,等价于 + ;

      (10)compareTo(String anotherString):比较两个字符串的大小;

      (11)substring(int beginIndex):返回一个从beginIndex开始截取的子字符串;

      (12)substring(int beginIndex , int endIndex):返回一个从beginIndex开始到(endIndex - 1)结束的子字符串;

      (13)endsWith(String suffix):测试此字符串是否以指定的后缀结束;

      (14)startsWith(String prefix):测试此字符串是否以指定的前缀开始;

      (15)startsWith(String prefix , int toffset):测试此字符串从指定索引位置开始的子字符串是否以指定的前缀开始;

      (16)contains(charSequence s):判断此字符串是否包含某字符串序列;

      (17)indexOf(String str):返回指定子字符串在此字符串中第一次出现的索引位置;

      (18)indexOf(String str , int fromIndex):返回指定子字符串在此字符串中从指定索引开始第一次出现的索引位置,

      (19)lastIndexOf(String str):从后往前找,返回指定子字符串在此字符串中倒序第一次出现的索引位置;

      (20)lastIndexOf(String str , int fromIndex):从后往前找,返回指定子字符串在此字符串中从指定索引开始倒序第一次出现的索引位置;

      (21)replace(char oldChar, char newChar):替换字符—返回将字符串中的oldChar全部替换为newChar后的字符串;

      (22)replace(CharSequence target, CharSequence replacement):替换字符串—返回将字符串中的target全部替换为replacement后的字符串;

      (23)replaceAll(String regex, String replacement):使用给定的replacement替换此字符串所有匹配给定的正则表达式的子字符串;

      (24)replaceFirst(String regex, String replacement):使用给定的replacement替换此字符串匹配给定的正则表达式的第一个子字符串;

      (25)matches(String regex):判断此字符串是否匹配给定的正则表达式;

      (26)split(String regex):根据给定正则表达式的匹配拆分此字符串;

      (27)split(String regex, int limit):根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部放到最后一个元素中。

public class Test{
    public static void main(String[] args) {
        String s1 = " Hello World ";
        String s2 = " hello world ";
        String s3 = "helloworld";

        System.out.println(s1.length());                //13
        System.out.println(s1.charAt(2));               //e
        System.out.println(s1.isEmpty());               //false
        System.out.println(s1.toLowerCase());           // hello world
        System.out.println(s1.toUpperCase());           // HELLO WORLD
        System.out.println(s1);                         // Hello World   s1不可变,仍为HelloWorld
        System.out.println(s1.trim());                  //Hello World
        System.out.println(s1.equals(s2));              //false
        System.out.println(s1.equalsIgnoreCase(s2));    //true
        System.out.println(s1.concat(s2));              // Hello World  hello world
        System.out.println(s1.compareTo(s2));           //-32 如果是负数,则s1小,是正数,则s1大,如果是0,则s1和s2相等
        System.out.println(s1.substring(4));            //lo World
        System.out.println(s1.substring(7,10));         //Wor
        System.out.println(s3.endsWith("ld"));          //true
        System.out.println(s3.startsWith("h"));         //true
        System.out.println(s3.startsWith("ll",2));      //true
        System.out.println(s3.contains("hello"));       //true
        System.out.println(s3.indexOf("l"));            //2
        System.out.println(s3.indexOf("l",5));          //8
        System.out.println(s3.lastIndexOf("l"));        //8
        System.out.println(s3.lastIndexOf("l",7));      //3
        System.out.println(s3.replace('l','T'));        //heTToworTd
        System.out.println(s3.replace("ll","TT"));      //heTToworld
    }
}

    3. String类与其他结构的转换:

      (1)String与基本数据类型、包装类的转换

               String转到基本数据类型、包装类:调用包装类的静态方法parseXxx()

               基本数据类型、包装类转换到String:调用String里重载的valueOf()

public class Test{
    public static void main(String[] args) {
        //String类型 转到 基本数据类型、包装类 : 调用包装类的parseXxx()
        String str1 = "123";
        int i1 = Integer.parseInt(str1);     //int i1 = (int)str1   是错误的

        String str2 = "true";
        boolean b = Boolean.parseBoolean(str2);

        //基本数据类型、包装类 转到 String类型 : 调用String里重载的valueOf()
        int i2 = 12;
        String str3 = String.valueOf(i2);   //str3为String类型

        Integer i3 = 12;
        String str4 = String.valueOf(i3);  //str4为String类型
    }
}

      (2)String与char[ ]之间的转换

               String转换到char[ ]:调用String的toCharArray();

               char[ ]转换到String:调用String的构造器;

import java.util.Arrays;

public class Test{
    public static void main(String[] args) {
        //String转换到char[]:调用String的toCharArray
        String str1 = "abc";
        char[] char1 = str1.toCharArray();
        System.out.println(Arrays.toString(char1));     //[a, b, c]
        
        char[] array2 = new char[]{'a','b','c'};
        String str2 = new String(array2);
        System.out.println(str2);                      //abc
    }
}

      (3)String与byte[ ]之间的转换

               String转换到byte[ ]:调用String的getBytes();

               byte[ ]转换到String:调用String的构造器;

import java.util.Arrays;

public class Test{
    public static void main(String[] args) {
        //String转换到byte[]:调用String的getBytes()
        String str1 = "hello";
        byte[] byte1 = str1.getBytes();
        System.out.println(Arrays.toString(byte1));     //[104, 101, 108, 108, 111] 对应每个字符的ASCII

        byte[] byte2 = new byte[]{104, 101, 108, 108, 111};
        String str2 = new String(byte2);
        System.out.println(str2);                      //hello
    }
}

四.  StringBuffer类和StringBuilder类

       String:不可变的字符序列,底层使用char[ ]储存;

                     String str1 = new String() ;               //char[] value = new char[0]

                     String str2 = new String("abc") ;       //char[] value = new char[]{'a','b','c'}

       StringBuffer:可变的字符序列、线程安全、效率低,底层使用char[ ]储存;

       StringBuilder:可变的字符序列、线程不安全、效率高,底层使用char[ ]储存,和StringBuffer一样;

                              StringBuffer sb1 = new StringBuffer();   //char[] value = new char[16]; 底层会初始化一个16长度的容量

                              sb1.append('a');     //value[0] = 'a';

                              StringBuffer sb2 = new StringBuffer("abc");  //char[] value = new char["abc".length + 16]

public class Test{
    public static void main(String[] args) {
        String str1 = new String("hello");
        str1.replace("h","m");
        System.out.println(str1);          //hello     不可变

        StringBuffer sb1 = new StringBuffer("hello");
        sb1.setCharAt(0,'m');
        System.out.println(sb1);          //mello      可变


        StringBuffer sb2 = new StringBuffer();
        System.out.println(sb2.length());   //0
        sb2.append('a');
        System.out.println(sb2);            //a
        System.out.println(sb2.length());   //1

        StringBuffer sb3 = new StringBuffer("abc");
        System.out.println(sb3.length());   //3
        sb3.append("def");
        System.out.println(sb3);            //abcdef
        System.out.println(sb3.length());   //6

    }
}

         StringBuffer和StringBuilder的常用方法:其包含String中的所有方法

        (1)append():用于进行字符串拼接

        (2)delete(int start, int end):删除指定位置的内容

        (3)replace(int start, int end, String str):把[start, end)的位置替换为str

        (4)insert(int offset, xxx):在指定位置插入xxx

        (5)reverse():把当前字符序列逆转

public class Test{
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("abcdef");

        sb.append(12);
        System.out.println(sb);       //abcdef12

        sb.delete(2,4);
        System.out.println(sb);       //abef12

        sb.replace(2,5,"cd");
        System.out.println(sb);       //abcd2

        sb.insert(4,"ef");
        System.out.println(sb);       //abcdef2

        sb.reverse();
        System.out.println(sb);      //2fedcba
    }
}

五.  关于时间的类

       1. Date类

           toString():显示当前的具体时间;

           getTime():获取当前对象对应的时间戳;

import java.util.Date;

public class Test{
    public static void main(String[] args) {
        //创建java.util.Date对象
        //创建一个对应当前时间的Date对象
        Date date1 = new Date();
        System.out.println(date1.toString());
        System.out.println(date1.getTime());

        //创建一个对应指定时间戳的Date对象
        Date date2 = new Date(1635920889539L);
        System.out.println(date2.toString());


        //创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(1635920889539L);
        System.out.println(date3.toString());


        //java.util.Date对象转换为java.sql.Date对象
        Date date4 = new Date();
        java.sql.Date date5 = new java.sql.Date(date4.getTime());

    }
}

       2. SimpleDateFormat类

           SimpleDateFormat类是对Date类的格式化和解析,格式化是将日期转换为字符串,解析是将字符串转换为日期。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test{
    public static void main(String[] args) {
        Date date1 = new Date();
        System.out.println(date1);
        
        //使用默认格式将日期格式化:日期转换为字符串
        SimpleDateFormat sdf = new SimpleDateFormat();  
        
        String str1 = sdf.format(date1);
        System.out.println(str1);

        //解析:将字符串转换为日期
        String str2 = "2021/10/25 下午12:13";
        try{
            Date date2 = sdf.parse(str2);
            System.out.println(date2);
        }catch (ParseException e){
            e.printStackTrace();
        }
    }
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test{
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date);

        //以指定方式进行格式化:调用带参构造器指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        String str = sdf.format(date);
        System.out.println(str);

        //解析
        try{
            Date date1 = sdf.parse("2021-10-25 12:13:00");
            System.out.println(date1);
        }catch (ParseException e){
            e.printStackTrace();
        }

    }
}

       3. Calendar类

import java.util.Calendar;
import java.util.Date;

public class Test{
    public static void main(String[] args) {
        //实例化Calendar类
        Calendar calendar = Calendar.getInstance();

        //get()方法
        int day = calendar.get(Calendar.DAY_OF_MONTH);  //返回当前时间是这个月的第几天
        System.out.println(day);     //3

        //set()方法
        calendar.set(Calendar.DAY_OF_MONTH,13);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);     //13

        //add()方法
        calendar.add(Calendar.DAY_OF_MONTH,3);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);    //16

        //getTime()方法
        Date date = calendar.getTime();
        System.out.println(date);

        //setTime()方法
        Date date1 = new Date();
        calendar.setTime(date1);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);     //13
    }
}

       4. LocalDate类、LocalTime类、LocalDateTime类

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

public class Test{
    public static void main(String[] args) {
        //LocalDate类、LocalTime类、LocalDateTime类具有相同的方法

        //now():获取当前时间
        LocalDate localDate = LocalDate.now();                 //获取当前日期
        LocalTime localTime = LocalTime.now();                 //获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now();     //获取当前日期和时间

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of():设置指定的时间
        LocalDate localDate1 = LocalDate.of(2021,10,25);
        LocalTime localTime1 = LocalTime.of(12,13,13);
        LocalDateTime localDateTime1 = LocalDateTime.of(2021,10,25,12,13,13);

        System.out.println(localDate1);
        System.out.println(localTime1);
        System.out.println(localDateTime1);

        //getXxx():获取相关属性
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getHour());

        //withXxx():设置相关属性   具有不可变性
        LocalDate localDate2 = localDate1.withDayOfMonth(11);
        System.out.println(localDate2);   //2021-10-11
        System.out.println(localDate1);   //2021-10-25

        //plusXxx():增加相关属性的值
        LocalDate localDate3 = localDate1.plusMonths(2);
        System.out.println(localDate3);   //2021-12-25
        System.out.println(localDate1);   //2021-10-25
        
        //minusXxx():减少相关属性的值
        LocalDate localDate4 = localDate1.minusDays(12);
        System.out.println(localDate4);  //2021-10-13
        System.out.println(localDate1);  //2021-10-25
    }
}

       5. Instant类

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Test{
    public static void main(String[] args) {
        //now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);

        //添加时间偏移量,获取本地所在位置的时间
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);

        //toEpochMilli():获取从某一个时间开始的毫秒数
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //ofEpochMilli():通过给定的毫秒数得到具体的时间
        Instant instant1 = Instant.ofEpochMilli(1635930405740L);
        System.out.println(instant1);
    }
}

六.  Java比较器

       1. Comparable接口(自然排序)

         (1)像String类、包装类都实现了Comparable接口,重写了compareTo(obj)方法,可以直接比较两个对象的大小,且按从小到大的顺序排列;

import java.util.Arrays;

public class Test{
    public static void main(String[] args) {
        String[] array = new String[]{"A","D","B","E","C"};
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));         //[A, B, C, D, E]
    }
}

         (2)对于自定义类,如果需要排序,需要让自定义类实现Comparable接口,重写compareTo(obj)方法,在方法中指明如何排序;

         (3)重写compareTo(obj)的规则:如果当前对象this大于形参对象obj,则返回正整数;如果当前对象this小于形参对象obj,则返回符整数;对象this等于形参对象obj,则返回0。

import java.util.Arrays;

public class Test{
    public static void main(String[] args) {
        Goods[] array = new Goods[5];
        array[1] = new Goods("huawei",4999);
        array[2] = new Goods("xiaomi",3598);
        array[0] = new Goods("iphone",6999);
        array[3] = new Goods("vivo",3869);
        array[4] = new Goods("oppo",3598);

        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        //[Goods{name = oppo, price = 3598.0}, Goods{name = xiaomi, price = 3598.0}, 
        // Goods{name = vivo, price = 3869.0}, Goods{name = huawei, price = 4999.0},
        // Goods{name = iphone, price = 6999.0}]
    }
}

class Goods implements Comparable{
    private String name;
    private double price;

    public Goods(){

    }

    public Goods(String name, double price){
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" + "name = " + name + ", price = " + price + "}";
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods){
            Goods goods = (Goods)o;
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else{
                return this.name.compareTo(goods.name);
            }
        }
        throw new RuntimeException("数据错误");
    }
}

       2. Comparator(定制排序)

         (1)重写compare(Object o1, Object o2)方法来比较o1和o2的大小,如果方法返回正整数,则表示o1大于o2;如果返回0,表示相等;如果返回负整数,则表示o1小于o2。

         (2)Comparator是临时性的比较,在有需要时创建比较方法,Comparable是永久的,任何地方都可以调用。

import java.util.Arrays;
import java.util.Comparator;

public class Test{
    public static void main(String[] args) {
        String[] array = new String[]{"A","D","B","E","C"};
        Arrays.sort(array, 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(array));    //[E, D, C, B, A]
    }
}
import java.util.Arrays;
import java.util.Comparator;

public class Test{
    public static void main(String[] args) {
        Goods[] array = new Goods[5];
        array[1] = new Goods("huawei",4999);
        array[2] = new Goods("xiaomi",3598);
        array[0] = new Goods("iphone",6999);
        array[3] = new Goods("vivo",3869);
        array[4] = new Goods("oppo",3598);

        Arrays.sort(array, new Comparator() {
            //按照商品名称从低往高排,再按照价格从高往低排
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Goods && o2 instanceof Goods){
                    Goods g1 = (Goods)o1;
                    Goods g2 = (Goods)o2;
                    if(g1.getName().equals(g2.getName())){
                        return Double.compare(g1.getPrice(), g2.getPrice());
                    }else{
                        return g1.getName().compareTo(g2.getName());
                    }
                }
                throw new RuntimeException("输入数据错误");
            }
        });

        System.out.println(Arrays.toString(array));
        //[Goods{name = huawei, price = 4999.0}, Goods{name = iphone, price = 6999.0}, 
        // Goods{name = oppo, price = 3598.0}, Goods{name = vivo, price = 3869.0}, 
        // Goods{name = xiaomi, price = 3598.0}]
    }
}

class Goods implements Comparable{
    private String name;
    private double price;

    public Goods(){

    }

    public Goods(String name, double price){
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Goods{" + "name = " + name + ", price = " + price + "}";
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods){
            Goods goods = (Goods)o;
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else{
                return this.name.compareTo(goods.name);
            }
            //return Double.compare(this.price,goods.price);
        }
        throw new RuntimeException("数据错误");
    }
}

七.  System类

public class Test{
    public static void main(String[] args) {
        String javaVersion = System.getProperty("java.version");
        System.out.println(javaVersion);

        String javaHome = System.getProperty("java.home");
        System.out.println(javaHome);

        String osName = System.getProperty("os.name");
        System.out.println(osName);

        String osVersion = System.getProperty("os.version");
        System.out.println(osVersion);

        String userName = System.getProperty("user.name");
        System.out.println(userName);

        String userHome = System.getProperty("user.home");
        System.out.println(userHome);

        String userDir = System.getProperty("user.dir");
        System.out.println(userDir);
    }
}

八.  Math类

     (1)abs:绝对值;

     (2)acos、asin、atan、cos、sin、tan:三角函数;

     (3)aqrt:平方根;

     (4)pow(double a, double b):a的b次幂;

     (5)log:自然对数

     (6)exp:e为底的指数

     (7)max(double a, double b)、min(double a, double b)

     (8)random():返回0到0.1的随机数

     (9)long round(double a):double型数据a转换为long型(四舍五入)

     (10)toDegrees(double angrad):弧度转换为角度

     (11)toRadians(double angrad):角度转换为弧度

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值