java basic review common classes

Posted by manamino on Thu, 18 Jun 2020 06:01:02 +0200

I java.lang Class in package does not need to import package

1. Features:

   java.lang Package is the core of Java language, which provides the basic classes in Java. Including basic Object Class, Class class, String Class, basic type wrapper Class, basic math Class and other basic classes.

2. 8 basic types of initialization default values:

Note: the default value of char type initialization is null (that is, '\ u0000')

Summary of eight basic data types in Java

No

data type

Size / bit

Encapsulation class

Default

Representable data range

1

Byte (bit)

8

Byte

0

-128~127

2

Short (short integer)

16

Short

0

-32768~32767

3

Int (integer)

32

Integer

0

-2147483648~2147483647

4

Long (long integer)

64

Long

0

-9223372036854775808~9223372036854775807

5

Float (single precision)

32

Float

0.0

1.4E-45~3.4028235E38

6

Double (double)

64

Double

0.0

4.9E-324~1.7976931348623157E308

7

Char (character)

16

Character

empty

0~65535

8

boolean

8

Boolean

flase

true or false

3. The default value of other types is null

2, Use of java classes

0. Object class:

Feature: the base class of all classes, even if inheritance is not displayed, inherits the Object class and owns the methods in the Object class.

 1 public final native Class<?> getClass()    //Return to this Object Runtime classes
 2  
 3 public native int hashCode()    //Returns the hash code of the object
 4  
 5 public boolean equals(Object obj)    //Determine whether other objects are "equal" to this object
 6  
 7 protected native Object clone() throws CloneNotSupportedException    //Create and return a copy of this object
 8  
 9 public String toString()    //Returns the string representation of the object
10  
11 public final native void notify()    //Wake up a single thread waiting on this object monitor
12  
13 public final native void notifyAll()    //Wake up all threads waiting on this object monitor
14  
15 public final native void wait(long timeout) throws InterruptedException    //Make the thread of the current object wait timeout Duration
16  
17 public final void wait(long timeout, int nanos) throws InterruptedException    //Make the thread of the current object wait timeout Duration, or other threads interrupt the current thread
18  
19 public final void wait() throws InterruptedException    //Make the thread of the current object wait 

1.Objects class:

 1 /**
 2  * 1.Objects Class: java.util.Objects
 3  * JDK1.7 Started to add a tool class
 4  * It is used to calculate the hashcode of an object, return the string representation of the object, compare two objects, etc
 5  * These methods are all null pointer safe
 6  */
 7 String s = null;
 8 String s1 = "s1";
 9 
10 //report errors: java.lang.NullPointerException,because s by null So no method can be called
11 //System.out.println(s.equals(s1));
12 
13 System.out.println(Objects.equals(s,s1));   //false

2.Date class:

1 /**
2  * 2.Date Class: date time class, java.util.Date
3  * Accurate to milliseconds
4  */
5 System.out.println(new Date());     //Show current date
6 System.out.println(new Date(1000000000L));   //Convert millisecond value to date
7 System.out.println(new Date().getTime());   //Convert the current system time to millisecond display
8 System.out.println(System.currentTimeMillis()); //Returns the current system time in milliseconds

3.DateFormat class:

 1 /**
 2  * 3.DateFormat Class: an abstract class for time / date formatting, java.text.DateFormat
 3  * effect:
 4  *      Format: Date > text, parse: text > date
 5  * Member method:
 6  *      String format(Date date): Convert date to string
 7  *      Date parse(String source): Parse string to date
 8  *
 9  * Since the DateFormat class is an abstract class, we use the SimpleDateFormat class to use the
10  * SimpleDateFormat Construction method:
11  *      SimpleDateFormat(String pattern)
12  * Parameters:
13  *      String pattern: Specified mode of delivery
14  * Mode: case sensitive
15  *      y  Year, m month, d day, H hour, m minute, s second
16  * General default mode:
17  *      yyyy-MM-dd HH:mm:ss
18  * The letter of the pattern cannot be modified, but the connector can be modified
19  *      yyyy Mm / dd / yyyy HH H mm min ss s
20  */
21 //format:
22 System.out.println(new SimpleDateFormat("yyyy year MM month dd day HH Time mm branch ss second").format(new Date()));
23 //Resolution:
24 System.out.println(new SimpleDateFormat("yyyy year MM month dd day HH Time mm branch ss second").parse("2019 December 26, 2008 18:33:35"));

4.Calendar Class:

 1 /**
 2  * 4.Calendar Class: calendar class, java.util.Calendar , abstract class, providing methods for operating calendar
 3  * Use the static method getInstance() to return a subclass object of the Calendar class
 4  * Common member methods:
 5  *      public int get(int field): Returns the value of the given calendar field
 6  *      public void set(int field,int value): Set the given calendar field to the given value
 7  *      public abstract void add(int field, int amount): Add or subtract the specified amount of time from the calendar field according to the rules of the calendar
 8  *      public Date getTime(): Returns a Date object representing this Calendar time value
 9  * Member method parameters:
10  *      int feild: The field of calendar class can be obtained by using the static member variable of Calendar Class
11  *      YEAR = 1  year
12  *      MONTH = 2 month
13  *      DATE = 5  day
14  *      DAY_OF_MONTH = 5 One day of the month
15  *      HOUR = 10       Time
16  *      MINUTE = 12     branch
17  *      SECOND = 13     second
18  */
19 Calendar c = Calendar.getInstance();
20 
21 //Return to current year
22 System.out.println(c.get(Calendar.YEAR));
23 
24 //Set current year
25 c.set(Calendar.YEAR,9999);
26 System.out.println(c.get(Calendar.YEAR));
27 
28 //Increase year
29 c.add(Calendar.YEAR,3);
30 System.out.println(c.get(Calendar.YEAR));
31 
32 //get date
33 System.out.println(c.getTime());

5.System class:

 1 /**
 2  * 5.System Class: get system related information or operating system operation, java.lang.System
 3  *
 4  */
 5 //Returns the system time in milliseconds
 6 System.out.println(System.currentTimeMillis());
 7 
 8 //Copy the data specified in the array to another array
 9 int[] src = {1,2,3,4,5};
10 int[] dest = {6,7,8,9,0};
11 System.arraycopy(src,0,dest,0,3);
12 System.out.println(Arrays.toString(dest));      //[1, 2, 3, 9, 0]

6.StringBuilder class:

 1 /**
 2  * 6.StringBuilder Class: string buffer, variable string, initial value is 16 characters
 3  * String Class immutable string
 4  */
 5 //Empty constructor
 6 StringBuilder bu1 = new StringBuilder();
 7 System.out.println(bu1);
 8 
 9 //Constructor with parameters
10 StringBuilder bu2 = new StringBuilder("abc");
11 System.out.println(bu2);
12 
13 //Chain programming
14 bu2.append(1).append(true).append("Hello");
15 System.out.println(bu2);
16 
17 //StringBuilder->String
18 String bu2tos = bu2.toString();
19 System.out.println(bu2tos);
20 
21 //String->StringBuilder
22 bu2.append(bu2tos);
23 System.out.println(bu2);

7. Packaging:

 1 /**
 2  * 7.Packaging: 8, java.lang in
 3  * Because the basic type is easy to use but there is no corresponding method to operate the basic type,
 4  * We define a class, encapsulate the basic data type and define some methods in this class for operation
 5  * Basic type packaging
 6  * byte                 Byte
 7  * short                Short
 8  * int                  Integer
 9  * long                 Long
10  * float                Float
11  * double               Double
12  * char                 Character
13  * boolean              Boolean
14  *
15  *
16  * Starting from JDK 1.5, it supports automatic packing and unpacking
17  * Packing: basic type - > Packing class
18  * Unpacking: packing type - > basic type
19  */
20 //int -> Integer
21 Integer i = Integer.valueOf(11111);
22 System.out.println(i);
23 
24 //String -> Integer
25 i = Integer.valueOf("22222222");
26 System.out.println(i);
27 
28 //Integer -> int
29 int num = i.intValue();
30 System.out.println(num);
31 
32 //Because generics must be non basic
33 ArrayList<Integer> list = new ArrayList<>();
34 
35 //Auto boxing: list.add(new Integer(1))
36 list.add(1);
37 //Automatic unpacking: list.get(0).intValue();
38 int a = list.get(0);
39 
40 //Basic type to string
41 String ss = 100 + "";
42 System.out.println(ss);
43 ss = Integer.toString(123);
44 System.out.println(ss);
45 ss = String.valueOf(444);
46 System.out.println(ss);
47 
48 //String to basic type
49 int nn = Integer.parseInt(ss);
50 System.out.println(nn);

8.UUID class:

  • A class that represents a universal unique identifier (UUID). UUID represents a 128 bit value.
  • Role: generate unique number
  • Common methods: UUID.randomUUID() used to generate unique numbers
1 UUID u;
2 for (int i = 0; i < 100; i++) {
3     u = UUID.randomUUID();
4     System.out.println(u.toString().replaceAll("-",""));
5 }

9.Format class:

  • The Format class is an abstract base class for formatting locale sensitive information, such as dates, messages, and numbers.
  • Subclass owned:
    • DateFormat: an abstract date class
      • SimpleDateFormat: a concrete class that formats and parses dates in a locale related way.
    • MessageFormat: provides a way to generate connection messages in a language independent way.
    • NumberFormat: an abstract base class for all numeric formats.
      • ChoiceFormat: a number that allows a format to be applied to a range.
      • DecimalFormat: used to format decimal numbers.

(1)ChoiceFormat:

Note:

  • Both arrays must be the same length to be formatted.
  • When the number is less than the first number of the array, the first number is output. Output the last number when the number is greater than the last number of the array.
  • Output rule: when and only when limit [j] < x < limit [j + 1], X matches j (i.e. output left digit)
1 double[] limits = {3, 4, 5, 6, 7, 8, 9};
2 String[] formats = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
3 ChoiceFormat format = new ChoiceFormat(limits, formats);
4 System.out.println(format.format(-100));    //Monday
5 System.out.println(format.format(3.6));     //Monday

(2)DecimalFormat:

  • Use '0' and 'x' to represent numbers, the difference is that 'x' will omit the redundant 0 at the end
 1 // Take integer part
 2 String s1 = new DecimalFormat("0").format(12345.1512134567);
 3 System.out.println(s1);//12345
 4 
 5 // 1 decimal place,rounding
 6 String s2 = new DecimalFormat("0.0").format(12345.1512134567);
 7 System.out.println(s2);//12345.2
 8 
 9 // Take 3 decimal places after the decimal point, and take 0 for the insufficient part
10 String s3 = new DecimalFormat("0.000").format(12345.1);
11 System.out.println(s3);//12345.100
12 
13 // percentage
14 String s4 = new DecimalFormat("0.0%").format(12345.1512134567);
15 System.out.println(s4);// 1234515.1%
16 
17 // Scientific counting
18 String s5 = new DecimalFormat("0.00E0").format(12345.1512134567);
19 System.out.println(s5);//1.23E4
20 
21 // Each three digits are separated by commas
22 String s6 = new DecimalFormat(",000.000").format(12345.1512134567);
23 System.out.println(s6);//12,345.151
24 
25 //3 decimal places after the decimal point, if it is 0, it will not be displayed
26 String s7 = new DecimalFormat("#.###").format(123.300);
27 System.out.println(s7);//123.3
28 
29 //Embed formatting in text
30 System.out.println(new DecimalFormat("Per second#.###Meters.").format(123.300));//123 per second.3 Meters.

9.Arrays class:

  • Arrays is a tool class for arrays, which can copy, transform, sort, search, compare, fill and other functions

(1) . copy

  • copyOfRange(int[] original, int from, int to):
    • The first parameter represents the source array
    • The second parameter indicates the start position (obtained)
    • The third parameter indicates the end position (not available)
 1 public class ArraysTest {
 2 
 3     public static void main(String[] args) {
 4         int a[] = new int[]{18, 62, 68, 82, 65, 9};
 5 
 6         //1.Arrays copy
 7         int[] b = Arrays.copyOfRange(a, 0, 3);
 8         for (int i : b) {
 9             System.out.print(i + " ");
10         }
11         System.out.println();
12 
13         //2.System copy
14         System.arraycopy(a, 0, b, 0, 3);
15         for (int i : b) {
16             System.out.print(i + " ");
17         }
18         
19     }
20 }

(2) . convert to string

 1 public class ArraysTest {
 2 
 3     public static void main(String[] args) {
 4         //1.Returns the string form of a one-dimensional array
 5         int[] a = new int[]{18, 62, 68, 82, 65, 9};
 6         System.out.println(Arrays.toString(a));
 7 
 8         //2.Returns the string form of a multidimensional array
 9         int[][][] b = {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, {{11, 12, 13}, {21, 22, 23}}};
10         System.out.println(Arrays.deepToString(b));
11         System.out.println(Arrays.toString(b));
12 
13         /**
14          * Output:
15          * [18, 62, 68, 82, 65, 9]
16          * [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[11, 12, 13], [21, 22, 23]]]
17          * [[[I@135fbaa4, [[I@45ee12a7]
18          */
19     }
20 }

(3) . array sorting

 1 public class ArraysSortTest {
 2 
 3     public static void main(String[] args) {
 4         //1.Arrays Own ascending sort
 5         Integer[] nums1 = {5, 2, 1, 3, 4, 9, 0, 7, 8, 6};
 6         Arrays.sort(nums1);
 7         System.out.println(Arrays.toString(nums1));
 8 
 9         //2.Custom class
10         Integer[] nums2 = {5, 2, 1, 3, 4, 9, 0, 7, 8, 6};
11         Comparator<Integer> comparator = new MyComparator();
12         Arrays.sort(nums2, comparator);
13         System.out.println(Arrays.toString(nums2));
14 
15         //3.Anonymous Inner Class 
16         Integer[] nums3 = {5, 2, 1, 3, 4, 9, 0, 7, 8, 6};
17         Arrays.sort(nums3, new Comparator<Integer>() {
18             @Override
19             public int compare(Integer a, Integer b) {
20                 return b - a;
21             }
22         });
23         System.out.println(Arrays.toString(nums3));
24 
25         //4.lambda expression
26         Integer[] nums4 = {5, 2, 1, 3, 4, 9, 0, 7, 8, 6};
27         Arrays.sort(nums4, (a, b) -> b - a);
28         System.out.println(Arrays.toString(nums4));
29     }
30 }
31 
32 
33 class MyComparator implements Comparator<Integer> {
34     @Override
35     public int compare(Integer a, Integer b) {
36         return b - a;
37     }
38 }

Add:

Comparison between Comparable and Comparator:

  • Comparable is a sort interface. If a class implements the comparable interface, it means "this class supports sorting". Comparator is comparator. If we need to control the order of a class, we can set up a comparator of this class to sort.
  • Comparable is equivalent to "internal Comparator", while Comparator is equivalent to "external Comparator".
  • The two methods have their own advantages and disadvantages. It is simple to use compatible. As long as the object of the compatible interface is implemented, it will become a Comparable object directly, but the source code needs to be modified. The advantage of using Comparator is that you don't need to modify the source code, but to implement a Comparator. When a custom object needs to be compared, you can compare the size by passing the Comparator and the object together, In Comparator, users can implement complex and universal logic by themselves, so that they can match some simple objects, which can save a lot of repeated work

(4) . search

Note: you must sort before searching

 1 public class ArraysTest {
 2 
 3     public static void main(String[] args) {
 4         int a[] = new int[]{18, 62, 68, 82, 65, 9};
 5 
 6         Arrays.sort(a);
 7         System.out.println(Arrays.toString(a));
 8 
 9         //Must sort before binary search
10         System.out.println("Where the number 62 appears in the array"+Arrays.binarySearch(a,62));
11 
12         /**Output:
13          * [9, 18, 62, 65, 68, 82]
14          * Number 62 in array position 2
15          */
16     }
17 }

(5) . determine whether the contents of two arrays are the same

 1 public class ArraysTest {
 2 
 3     public static void main(String[] args) {
 4         int a[] = new int[]{18, 62, 68, 82, 65, 9};
 5         int b[] = new int[]{18, 62, 68, 82, 65, 9};
 6         int c[] = new int[]{99, 62, 68, 82, 65, 8};
 7 
 8         System.out.println(Arrays.equals(a,b));
 9         System.out.println(Arrays.equals(a,c));
10         System.out.println(Arrays.equals(b,c));
11 
12         /**
13          * Output:
14          * true
15          * false
16          * false
17          */
18     }
19 }

(6) . filling

 1 public class ArraysTest {
 2 
 3     public static void main(String[] args) {
 4         int[] a = new int[10];
 5 
 6         //1.Fill all
 7         Arrays.fill(a, 5);
 8 
 9         System.out.println(Arrays.toString(a));
10 
11         /**
12          * Output:
13          * [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
14          */
15 
16         //2.Fill subscript[2,4]Is 1
17         Arrays.fill(a, 2, 5, 1);
18         System.out.println(Arrays.toString(a));
19 
20         /**
21          * Output:
22          * [5, 5, 1, 1, 1, 5, 5, 5, 5, 5]
23          */
24     }
25 }

Topics: Java Programming JDK less