Common methods in JAVA classes!!! (Objects class and Object class)

preface

The so-called tool class means that the methods in this class are modified by static and can be called directly through the class name. The advantage is that there is no need to create objects; It simplifies our use to a certain extent The following summarizes several common tool classes and methods in java!!!

1, Arrays tool class

(1)sort method

-  public static void sort(array)In ascending order by default,Sort array elements 

	int [] array1 = {2,5,3};
	arrays.sort(array1);//Order directly in the original array

be careful:

  • If it is a string array, sort defaults to ascending alphabetical order;
  • If it is a custom type, the custom class needs to be supported by the comparable or comparator interface

(2)toString method

-  public static String toString(array);default format:[Element 1,Element 2,......]

This method can convert an array to a string

2, Objects class and Object class

Objects class

An Objects tool class is added in JDK7. It provides some methods to operate Objects. It is composed of some static practical methods. These methods are null save (null pointer safe) or null tolerance (null pointer tolerant), which are used to calculate the hashcode of the object, return the string representation of the object, and compare the two Objects.

When comparing two Objects, the equals method of Object is easy to throw null pointer exceptions, and the equals method in the Objects class optimizes this problem. The method is as follows:

  • public static boolean equals(Object a, Object b): judge whether two objects are equal.

We can check the source code and learn:

public static boolean equals(Object a, Object b) {  
    return (a == b) || (a != null && a.equals(b));  
}

Object class

java.lang.Object class is the root class in the Java language, that is, the parent class of all classes. All method subclasses described in it can be used. When an object is instantiated, the final parent class is object.

(1)equals method

  • public boolean equals(Object obj): indicates whether another object is "equal" to this object.

If you call the member method equals and specify another object as the parameter, you can judge whether the two objects are the same. The "same" here has two methods: default and custom.

Default address comparison

If the equals method is not overridden, the Object address comparison of the = = operator is performed by default in the Object class. As long as the Object is not the same Object, the result must be false.

Object content comparison

If you want to compare the contents of objects, that is, if all or some of the specified member variables are the same, you can override the equals method. For example:

(2)toString method

  • public String toString(): returns the string representation of the object.

The toString method returns the string representation of the object. In fact, the content of the string is the type + @ + memory address value of the object.

Because the result returned by toString method is the memory address, and in development, it is often necessary to get the corresponding string representation according to the object properties, so it also needs to be rewritten.

public class Person {  
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
    }

    // Omit constructor and Getter Setter
}

3, System class

(1) currentTimeMillis method

`public static long currentTimeMillis()`: Returns the current time in milliseconds.

In fact, the currentTimeMillis method is to obtain the millisecond difference between the current system time and 00:00 on January 1, 1970. This method can be used to calculate the time consumed by a program

The time (in milliseconds) it takes to verify that the for loop prints numbers 1-9999

public class SystemTest1 {
    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("Total time taken MS:" + (end - start));
    }
}

(2)arraycopy method

  • Public static void array copy (object SRC, int srcpos, object DeST, int destpos, int length): copies the data specified in the array to another array.
Parameter serial numberParameter nameParameter typeParameter meaning
1srcObjectSource array
2srcPosintSource array index start position
3destObjecttarget array
4destPosintTarget array index start position
5lengthintNumber of copied elements

Copy the first three elements of src array to the first three positions of dest array. Before copying elements: src array elements [1,2,3,4,5], dest array elements [6,7,8,9,10]. After copying elements: src array elements [1,2,3,4,5], dest array elements [1,2,3,9,10]

import java.util.Arrays;

public class Demo11SystemArrayCopy {
    public static void main(String[] args) {
        int[] src = new int[]{1,2,3,4,5};
        int[] dest = new int[]{6,7,8,9,10};
        System.arraycopy( src, 0, dest, 0, 3);
        /*After the code runs: the elements in the two arrays have changed
         src Array elements [1,2,3,4,5]
         dest Array elements [1,2,3,9,10]
        */
    }
}

4, Collections class

Collections class is a tool class used to operate collections, including the following common methods:

  • Public static < T > Boolean addall (collection < T > C, t... Elements): add some elements to the collection.
  • Public static void shuffle (list <? > list): disrupt the order of the collection.
  • Public static < T > void sort (list < T > list): sort the elements in the collection according to the default rules.
  • Public static < T > void sort (list < T > list, comparator <? Super T >): set the elements in the collection according to the specified rules

(1)addAll method

public class CollectionsDemo {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        //Original writing
        //list.add(12);
        //list.add(14);
        //list.add(15);
        //list.add(1000);
        //Use the tool class to add elements to the collection  
        Collections.addAll(list, 5, 222, 1,2);
        System.out.println(list);
        //Sorting method 
        Collections.sort(list);
        System.out.println(list);
    }
}
result:
[5, 222, 1, 2]
[1, 2, 5, 222]

(2)sort method

1. Public static < T > void sort (list < T > list) this method sorts according to the default rule, that is, ascending order

Note: the premise of using this method:
The elements stored in the sorted collection must implement the comparable interface and override the compareTo method

class Person implements Comparable<Person>{

	private int age;
	private String name;

	.....
	ellipsis get/set method
	public int compareTo(Person o){
		return this.getAge() - o.getAge();
		//return o.getAge() - this.getAge();
		//return 0;

	}

}
Arraylist<Person> list = new ArrayList<>();
Collections.sort(list);

A person class is defined, the comparable interface is implemented, and the compareTo() method is implemented
Collation:

  • this.xxx - parameter: represents ascending order
  • Parameter - this XXX: for descending order
  • Return 0: represents the same element

    2.public static <T> void sort(List<T> list,Comparator<? super T> )
    Note: since the first method is to implement the comparable interface, this comparison method requires the sorted class to implement the interface and rewrite the method;
    The other method is to sort with the help of a comparator. At this time, the compare method needs to be rewritten
class Person{

	private int age;
	private String name;

	.....
	ellipsis get/set method
}
Arraylist<Person> list = new ArrayList<>();
Collections.sort(list,new Comparator<Person>(){

	public int compare(Person o1,Person o2){
		return o1-o2;
	} 

//In addition, we can expand this method
//If the age is the same, sort by name
	/*public int compare(Person o1,Person o2){
	   int result = o1.getAge()-o2.getAge();
		if(result == 0){
			result = o1.getName() - o2.getName();
		}
		return result;
	} 
*/
});

Collation:
o1 - o2: represents ascending order
o2 - o1: represents descending order

The difference between comparable and comparator

The Comparable interface is located in Java Lang package, the Comparator interface is located in Java Util package.

Comparable:    Internal comparator,
A class if you want to use Collections.sort(list) Method,
You need to implement this interface

Comparator:    External comparator
 For those not implemented Comparable Interface
 Or for what has been achieved Comparable The sorting rule in is not satisfactory.
It is more flexible without changing the structure of the class. (policy mode)

Tags: Java comparator

Posted by Crashthatch on Tue, 19 Apr 2022 09:39:13 +0930