Three of the commonly used classes of Java-other classes (interfaces)

1、Comparable 或 Comparator

Using
objects in background Java, under normal circumstances, you can only compare: == or! =. Cannot use> or <,
but in the actual development scenario, we need to sort multiple objects, the implication is that you need to compare the size of the object.
How to achieve? Use either of two interfaces: Comparable or Comparator

1.1 Examples of using the Comparable interface: natural ordering

1. Like String, wrapper, etc., implements the comparable interface, rewrites compareTo () method, and compares the size of two objects.

2. Rewrite the rules of the compareTo () method:
If the current object this is greater than the formal parameter object obj, a positive integer is returned.
If the current object this is less than the formal parameter object obj, a negative integer is returned
. Returns 0

3. After rewriting compareTo () like String and wrapper, it will sort from small to large

4. For custom classes, if you need to sort, you can let the custom class implement the Comparable interface, override the compareTo () method, and specify how to sort in the compareTo () method

public class Goods implements Comparable {
    private String name;
    private double price;
    //省略了 getter setter 构造器  toString方法	
    //重写了compareTo()方法
     @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 0;
                return -this.name.compareTo(goods.name);
            }
            //方法二
//           return Double.compare(this.price,goods.price)
        }
//        return 0;
        throw  new RuntimeException("传入的数据类型不一致");
    }
    }
   Goods[] arr = new Goods[5];
        arr[0] = new Goods("lenovoMouse", 46);
        arr[1] = new Goods("xiaomiMouse", 12);
        arr[2] = new Goods("dellMouse", 35);
        arr[3] = new Goods("huaweiMouse", 65);
        arr[4] = new Goods("MicrosoftMouse", 35);

        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
1.2, the use of Comparator interface, custom sorting

1. Background
When the type of the element does not implement the java.lang.Comparable interface and it is inconvenient to modify the code
or the sorting rules of the java.lang.Comparable interface are not suitable for the current operation,
then consider implementing the Comparator object to sort
2. Rewrite The compara (Object o1, Object o2) method compares the size of o1 and o2.
If a positive integer is returned, it means that o1 is greater than o2.
If it returns 0, it means that it is equal. A
negative integer is returned, which means that o1 is less than o.

        String[] arr = new String[]{"AA", "CC", "JJ", "MM", "DD", "KK"};
       Arrays.sort(arr, new Comparator<String>() {
           //按照字符串从大到小的排序
           @Override
           public int compare(String o1, String o2) {
               if ( o1 instanceof String && o2 instanceof String){
                   String s1 = (String) o1;
                   String s2 = (String) o2;
                   return -s1.compareTo(s2);
               }
//                return 0;
               throw new RuntimeException("输入的数据类型不一致");
           }
       });
       Arrays.sort(arr);
       System.out.println(Arrays.toString(arr));

2. Use of other commonly used classes

2.1、System

① System represents the system where the program is located, and provides corresponding system attribute information and system operations. The System class cannot manually create objects because the constructor is decorated with private, preventing the outside world from creating objects. All the methods in the System class are static methods, and the class name can be accessed.
② Common methods
1. Obtain the current millisecond value of the system (public static long currentTimeMillis ())

Get the difference between the current system time and the milliseconds before 00:00 on January 01, 1970, we can use it to test the execution time of the program

public static void main(String[] args) {
     long start = System.currentTimeMillis();
    for (int i=0; i<10000; i++) {
         System.out.println(i);
}
long end = System.currentTimeMillis();
System.out.println("共耗时毫秒:" + (end-start) );
}

2. End the running Java program (public staitc void exit (int status))

The parameter can be passed in a number. Normally, the incoming 0 is recorded as a normal state, and the others are abnormal.

3. Garbage collector (public static void gc ())

Used to run the garbage collector in the JVM to complete the removal of garbage in memory.

4. Determine the current system properties (public static getProperties getProperties ())
System.out.println (System.getProperties ());

2、Math

① The Math class in Java encapsulates commonly used mathematical operations and provides basic mathematical operations, such as exponential, logarithmic, square root, and trigonometric functions. The Math class is located in the java.lang package, and its constructor is private, so it is not possible to create objects of the Math class, and all methods in the Math class are class methods, which can be called directly by the class name.

② Method
Math.abs find the absolute value
Math.sin sine function Math.asin inverse sine function
Math.cos cosine function Math.acos inverse cosine function
Math.tan tangent function Math.atan inverse tangent function Math.atan2 inverse tangent function
Math .toDegrees radians are converted to degrees Math.toRadians angles are converted to radians
Math.ceil Get the largest integer
not less than a certain number Math.floor Get the largest integer not greater than a certain number
Math.IEEEremainder Find the remainder
Math.max Find the largest
Math of the two numbers . seeking the minimum of two numbers min
Math.sqrt requirements prescribe
Math.pow arbitrary power demand of a number of processing overflow exception is thrown ArithmeticException
Math.exp arbitrary power demand e
Math.log10 base 10 logarithm
Math. log natural log
Math.PI recorded pi
Math.E constants recorded e
Math also has some similar constants, are some commonly used quantities of engineering mathematics.
Math.rint finds the nearest integer (may be larger or smaller than a certain number)
Math.round Same as above, returns int or long (the previous function returns double)
Math.random returns 0, 1 Random number

Usage example:
double s = Math.sqrt (5);
double x = Math.pow (2,4) // Calculate 2 to the 4th power

3、BigInteger 和 BigDecimal

The content of this class can be viewed: https://blog.csdn.net/qq997404392/article/details/78085783
In Java's integer type, byte is 8 bits, short is 16 bits, int is 32 bits, long is 64 bits . Because the binary digits of these values ​​have been fixed, the size of the value they can represent has a certain range limit. Therefore, Java provides BigInteger class and BigDecimal class to handle larger numbers.

One of the commonly used classes in Java-String, StringBuffer, StringBuilder

https://blog.csdn.net/weixin_43244120/article/details/105187804

Java's commonly used class two-date time class

https://blog.csdn.net/weixin_43244120/article/details/105188644

Published 19 original articles · praised 0 · visits 487

Guess you like

Origin blog.csdn.net/weixin_43244120/article/details/105189069