Puge java high-level integration

Reading guide

	The blogger has sorted out some common grammar candy in the review stage these two days, so let's follow me to have a look java What are the common grammatical sugars in

The simple understanding of syntax sugar in java is some special syntax in java. It can help us better understand the code, improve the readability of the code, and improve the efficiency of programming. For details, please go to Baidu Encyclopedia Grammar sugar More detailed introduction.
Note: because their jdk versions are different, you must compare your own jdk version when using it. I will also mark the jdk version number below.

Specific classification

These syntax sugars include conditional compilation, assertion, combination of Switch statement with enumeration and string, variable parameters, automatic boxing / unpacking, enumeration, internal classes, generic erasure, enhanced for loop, lambda expression, try with resources statement, and so on
Here I will briefly introduce several

for - each(JDK5.0)

The first is our most commonly used for - each, whose syntax is very similar to the for loop. It is a new circular way of traversing arrays based on the extension of the for loop in C language.

In essence for - each The bottom layer of is implemented by iterators, so let's take a look at its specific use in the previous section of code
    @Test
    public void each(){
        String[] each = {"hello", "java", "word"};
        List<String> list =  Arrays.asList(each);
        for (Object s : list) {
            System.out.println(s);
        }

So when do we use it? Let's first look at the advantages and disadvantages of for - each

advantage

  • Grammar introduction
  • There is no need to care about the subscript out of bounds exception in the traversal process
  • When using loop traversal, the performance is similar to that using the for loop

shortcoming

  • each cannot delete / replace elements
  • Unable to get current index
  • Forward traversal only
  • You cannot traverse two collections at the same time

In the actual development, I listed three types of formations that can be applied to the scenario of for - each

  • array
  • Collection class
  • Any custom class that implements the Iterable interface

Automatic packing and unpacking (JDK5.0)

The simple understanding of automatic packing is to automatically convert the basic data type into the packing type, and unpacking is the process of converting the reference type into the basic data type

First of all, we need to know the eight basic data types and the corresponding figure of their reference types.

So what is automatic packing and unpacking?

Here is a simple example:
The process of converting an int variable into an Integer object is called boxing. On the contrary, the process of converting an Integer object into an int type value is called unpacking.

Let me briefly introduce the application scenarios of automatic packing and unpacking

  • When using a java collection, you cannot directly pass the basic data type into the collection, because the collection only accepts objects, so we will use automatic boxing and unpacking at this time. This is why we can directly add a basic data type without reporting an error
  • When we compare basic data types with reference data types "= ="
  • When calling some methods

Finally, let's briefly talk about some of its shortcomings

Objects will be created in the process of automatic boxing. Frequent boxing operations will consume a lot of memory and increase the pressure of GC (I will detail a blog about GC here), which will affect the performance.
If we do not initialize a value, there will be confusion.

Enumeration class (JDK 8)

First, let's look at a piece of code

public class shootGame extends JPanel {
    public static final int WIDTH = 400; //Width of panel
    public static final int HEIGHT = 654; //Length of panel

   
    //    Define the state of the game
    public static final int START = 0; // start
    public static final int RUNNING = 1; // function
    public static final int PAUSE = 2; // suspend
    public static final int GAME_OVER = 3; // end
 }

The above is some of the states in the game I did. However, when calling, I want to know what the state transition is and print out the state transition. We need to use some method encapsulation and private to prevent the outside world from creating private classes. This is obviously very troublesome.

At this time, we need a class to simplify this operation
public enum Type {
    START(1), RUN(2), PAUSE(3), GAME_OVER(4);

    private int Value;

    private Type(int Value) {
        this.Value = Value;
    }

}

However, you should pay attention to the following points when using enumeration classes:

  • Be sure to put the definition of enumeration class variables on the first line and end with a semicolon.
  • The constructor needs to be privatized. It is privatized by default. Even if you don't write it, it will default to private.

try-with-resource(JDK 7.0)

Try with resource is a new exception handling mechanism in JDK7. Its function is to close the resources used in the try - catch statement block.

java1.7 A new feature introduced in the version of: multiple exceptions are juxtaposed together

The example code is as follows:
  try {
            background = ImageIO.read(shootGame.class.getResource("Img/background(1).png"));

        } catch (IOException e | RuntimeException r){
            e.printStackTrace();
        }
      
 It should be noted that multiple exceptions in parallel cannot have (direct)/Indirect) inheritance relationship, otherwise an error will be reported       

Let's put an exception diagram

Numeric literal underscore (JDK 7.0)

As follows, when we define a quantity, the value is more than the number of bits (for example, the integer type is assigned with binary)
At this time, we can add some underscores in them to increase the readability of the values

//        Value of π
        double pi = 3.14_15_92_65_36;
//        A 32-bit binary number with the highest bit being the sign bit.
        int binVal = 0B1000_0000_0000_0000_0000_0000_0000_0011;
        System.out.println(pi);
        System.out.println(binVal);

Note: This underline can only be placed in the middle of the number


The above figure shows the operation result, which is no different from the normal output

But doing so can more intuitively see the number of digits. In general, this grammar candy is very good

var(JDK 10)

This syntax sugar is a relatively new feature of java. Its implementation depends on the jvm to automatically set its types.

So why do we need to use var?

Prime minister, we should know that java is a strongly typed language. Once a variable is defined, it will always be the data type if it does not undergo forced type conversion. var is a unique definition method of weakly typed language (for example, defining a variable in js). The advantage of this syntax sugar is that it assigns values to you through the automatic judgment of the jvm. Once the variable is defined, the type is clear and can not be changed again.

First, let's look at its example code

        var s = "lalla";
        var i = 123;
        i = "sss";//erro can no longer assign other types of values to it
        var user = new UserDetailsOInterest();
     

So here are some of its benefits

  • This avoids type redundancy (such as a long reference type name)
  • Align variable names
  • Make it easier to read

But it also has some limitations and disadvantages

It is best used in local variables
After a variable is determined, its type cannot be inferred
If a type is inferred, it can no longer assign other types to the value
Compound syntax cannot be used
Cannot use null
Try to avoid extensive use, which will make the readability of the code worse
Cannot be used in return types

Switch Expressions(JDK 12)

Not much to say, let's start with an example code

 		/**
         * Judge the number of days in the entered month
         */
        switch (s) {
            case "JAN":
            case "Mar":
            case "May":
            case "Jul":
            case "Aug":
            case "Oct":
            case "Dec":
                System.out.println(31);
                break;
            case "Feb":
                System.out.println(29);
                break;
            case "Apr":
            case "Jun":
            case "Sept":
            case "Mov":
                System.out.println(30);
                break;
            default:
                System.out.println("Please enter the correct month");
        }
        

You can see that this writing is very redundant and error prone

So let's take a look switch This sugar
        /**
         * Judge the number of days in the entered month
         */
        int i = switch (s) {
            case "JAN", "Mar", "May", "Jul", "Aug", "Oct", "Dec" -> 31;
            case "Feb" -> 28;
            case "Apr", "Jun", "Sept", "Mov" -> 30;
            default -> {  
				System.out.println("Please enter the correct month");
			}
     
        };
        System.out.println(i);

When the same case has the same expression function, it is obvious that the following logic is clearer and more complex with the logical judgment of the developer, which not only reduces the amount of code but also improves the efficiency.

So let's briefly summarize some precautions it needs

  • The corresponding multiple case s are merged into one piece to increase the readability of the code
  • Conditions are connected between actions with - > and if a matching branch is encountered, it will jump out of the branch directly without writing a break.
  • Each - > can only be followed by an expression, code block, or throw statement.

Normal form (JDK5.0)

First, let's look at an example code

  @Test
    public void normalForm() {
        List s = new ArrayList();
        s.add(1);
        s.add("2");
        s.add('a');
        s.add(true);
        for (Object o : s) {
            System.out.println("Define set output o:"+o);
        }
    }
Instantiate a in the collection ArrList time add Method can be compiled when adding elements, but an error will be reported when running


Therefore, the role of paradigm is highlighted at this time

  1. Its main function is to check type safety at compile time, and all forced type conversions are automatic and hidden
  2. Its principle is "type parameterization", which regards type as a parameter. In other words, the data type to be operated on is regarded as a parameter, just as the formal parameter of a method is a placeholder passed at run time.

OK, let's add the paradigm next, but there are many points to pay attention to!

  1. standard
    -Classes: Arraylist, HashSet, HashMap
    -Methods: cooletions.binarysearch, Arrays.sort
    -Interface: List, Iterator

  2. Application scenario of paradigm
    -The generic method is used when the added type constraint only acts between multiple parameters of a method
    -The method to add a type constraint is a static method, which can only be defined as a generic method, because a static method cannot use its type parameter

/*
* For example, if you want to output like this, add < T > in front of the static keyword of the static method and declare it as a generic method
*/
class A<T> {
    private static T a;
    public static void a() {
        System.out.println(a);
    }
}

OK, that's all for the basic introduction of grammar sugar~~

-----------------

Like, don't forget the third company ♥ ------------------—

Tags: Java JavaEE data structure Back-end

Posted on Mon, 29 Nov 2021 15:52:00 -0500 by patrikG