preface

A search on the Internet to learn Java will pop up numerous articles, but all are training institutions of the outline, it is chicken, did not write a word is to help novice how to know Java, so I think to write a real sense of Java from 0 to 1 article, help 0 basic white and beginner fiscal year to open the Java door

If you observe the java-related job requirements on recruitment websites, you will find that there are some common points in terms of technology or knowledge, regardless of other experience and ability.

  • Java based
  • Computer Fundamentals
  • Database, SQL/NoSQL
  • Common Open Source Frameworks
  • Distributed/microservices
  • Middleware, caching, messaging middleware

Learning any programming language, the first thing to learn is the basic grammar, the first step to open Java learning, of course, is to deeply grasp the computer foundation, programming basic grammar, object-oriented, collection, IO flow, threads, concurrency, exceptions and network programming, which we call JavaSE foundation. When you master these contents, you can make such as: installed on the computer thunderbolt download software, QQ chat client, attendance management system and other desktop software.

And this article is to write, is the Java foundation, if some people read it will continue to write computer foundation, database and framework these.

At the end of the article, I also compiled a book list of The Java Architect learning Core book list. You can buy it according to your own learning progress. If you are a student or have a tight budget recently, it doesn’t matter.

  • 22 Java Architect Core books
  • Learning routes and materials from 0 to 1Java
  • 1000+ questions from 2021

Don’t say more words, sit firmly help good, start!

Java basic syntax

The concept and characteristics of keywords

Concepts: Java keywords are predefined and have special meaning to the Java compiler. They are used to represent a data type, the structure of a program, etc. Keywords cannot be used as variable names, method names, class names, package names, and parameters.

Features:

  • All lowercase
  • Special colors are available in enhanced notepads (such as Notepad++)

2. Concepts and rules of identifiers

What is an identifier?

Anything that can be named by itself is called an identifier.

Example: project name, package name, class name. Method name

Naming conventions

(1) You cannot use Java keywords and reserved words, but you can include them.

② Can use 26 letter case, numbers 0-9,$and _.

③ Numbers can be used, but not in the first place.

④ There is no limit to the length in theory, but the naming should best reflect its role, follow the “hump form”, see life know meaning

⑤ All package names are lowercase, and all class names are big camel

⑥ The variable name and method name must start with a lowercase letter. If the name consists of multiple words, each word must start with a lowercase letter ****

(7) The name of the constant (especially the constant modified by final) is all capitalized. If it is a single letter, it needs to be capitalized. If it is multiple words, it needs to be separated by underscores. And they’re all uppercase

Example: Write an Ajax project instance,

Project name :ajaxtest Package name :com.liu. Ajax class name :AjaxDemoCopy the code

Constants & variables

Concept of constant: during the execution of the program. Fixed quantity.

Classification of constants:

  • Character constants: Any single character enclosed in single quotes is a character constant. For example:, ‘b’,’ 9 ‘, ‘middle’
  • String constants: Parts enclosed in double quotes are called string constants. For example: “ABC”, “Hello “, “123”
  • Integer constant: A number written directly without a decimal point. For example, 100, 200, 0, and -250
  • Floating-point constant: A number written directly with a decimal point. For example, 2.5, -3.14, 0.0
  • Boolean constants: there are only two values true | false

Basic data types:

Matters needing attention:

  • The default type in Java is int and double

  • The data range is not necessarily related to the number of bytes, for example, float is more extensive than long, but float is 4 bytes and 1ONG is 8 bytes.

  • Floating point may be an approximation, not an exact value.

  • The default type for floating-point numbers is double. If you must use float, you need to add the suffix F.

  • A string is not a primitive type, but a reference type

  • If it is an integer, the default type is int, and if you must use long, you need to add the suffix L. Uppercase suffixes are recommended.

Variable: The amount of content that can be changed during program execution.

Create a variable and use the following format:

Data type variable name; // create a variable

Variable name = data value; // Assign the data value on the right to the variable on the left

One-step format: data type variable name = data value; // When creating a variable, immediately put in the specified data value

Matters needing attention:

1. If you create multiple variables, the names of the variables must be unique.

2. For float and long types, do not discard the letter suffix F and L.

3. Variables that are not assigned cannot be used directly. It must be assigned before it can be used.

** Scope :** starts on the line that defines the variable and ends with the curly brace to which it belongs.

Data type conversion

Data type conversions occur when the validity types are different

Automatic type conversion (implicit)

1. Features: the code does not need special processing, automatic completion

2. Rules: Data ranges from small to large

Long num1 = 100; System. Out.println (num1)Copy the code

// The left side is long and the right side is default int

// int–>long

Cast (explicit)

1. Features: The code needs special formatting processing and cannot be completed automatically

2. Format: small range type Small range variable name = (small range type) originally large range of data

Int num= (int) 100L; System.out.print1n (num);Copy the code

// The left side is int and the right side is long

// Small variable name = (small type) originally large data;

Matters needing attention:

1. Cast is not recommended because of the possibility of precision loss and data overflow.

2. Byte/short/char all three types can perform mathematical operations, such as addition “+”.

3. The three byte/short/char types are upgraded to int types before they are evaluated. Conforms to the ASCII code table.

Example 3: byte num4 = 40; / / attention! The value on the right cannot exceed the type range on the left byte num5 = 50. Int result1 = num4 + num5; int result1 = num4 + num5; System.out.println (result1); / / 90Copy the code

Operator: symbol that performs a particular operation. For example: +

Expressions: Expressions connected by operators are called expressions. For example, 20+5. Another example: A + B

Four operations: plus + minus – multiply * divide /

Take modulus (take remainder) : %

Modulo operators have a remainder only for division of integers.

Int x = 10; Int y = 3; Int resultl = x/y; System.out.println (result1); //3 int result2 = x % y; System.out.println (result2); // Remainder, modulus, 1Copy the code

Arithmetic operator

 

The plus sign “+” in the four operations has three common uses:

1. For numbers, + is addition.

2. For char types, char is promoted to int before being evaluated, and then evaluated. Char char char char char char char char char char

3. For the String String, + represents String concatenation. The () parentheses have the highest precedence

String str = "Java"; //String + int --> String system.out.println (str2+20); //String + int --> String system.out.println (str2+20); //Java20Copy the code

Increment operator: ++

For example: +; Use a first, then a = a + 1;

int a = 1; int b = 2; b = a++; // In this step, the value of A has not changed, so a=1 is assigned to B and then changed. System.out.println("a:"+a); //a:2 System.out.println("b:"+b); //b:1Copy the code

Decrement operator: – –

For example: ++a; A = a + 1; Let’s use the a value.

int a = 1;
int b = 2;
b = --a;
System.out.println("a:"+a);
System.out.println("b:"+b);
Copy the code

A++ : a value that is incremented after the value of a variable is used

++a: Increments a variable value before it is used

    • The operator works in the same way, except that it performs a reduction rather than a increment.

The assignment operator

An assignment operator is a symbol that specifies a value for a variable or constant. For example, we can use “=” to assign the result of the expression on the right to the operand on the left.

The common assignment operators supported by Java are shown in the following table:

Comparison operator

The comparison operator is used to determine the size of two pieces of data, such as greater than, equal to, or not equal to. The result of the comparison is a Boolean value (true or false).

The comparison operators commonly used in Java are shown in the following table:

Matters needing attention:

1, >, <, >=, <= only the left and right operands can be numeric

== =! The operands on either side of = can be numeric or reference types

Logical operator

Used mainly for logical operations, join two Boolean values, representing two conditions.

Logical operators commonly used in Java are shown in the following table:

We can understand logical operators in terms of “voting” :

Everyone is required to vote to approve an issue

You can pass an issue by asking only one person to vote for it

3, non: a person originally voted to agree, through the non operator, can make their vote invalid

4. Xor: An issue can be passed if one and only one person votes for it

When using logical operators, we encounter an interesting “short-circuit” phenomenon >> If the end result is already known from the left side, the code on the right side will no longer execute, saving some performance.

For example, in (1 > 2) && (1 < 3), if we can determine that 1 > 2 on the left is false, then there is no need to execute 1 < 3 on the right.

Conditional operator

The conditional operator (? 🙂 also known as the “ternary operator”.

  • Unary operator: An operator that requires only one piece of data to operate on. For example: invert! , self-increasing ++, self-decreasing —

  • Binary operator: An operator that requires two pieces of data to operate. For example, add + and assign =

  • Ternary operator: An operator that requires three pieces of data to operate.

Syntax: Boolean expressions? Expression 1: expression 2

Operation: Returns the value of expression 1 if the Boolean expression is true, otherwise returns the value of expression 2

Such as:

Since the expression 8>5 has the value true, it returns 8 greater than 5

Methods ♦ ♦

The so-called method is an ordered combination of code used to solve a class of problems. It is a functional module.

In general, the syntax for defining a method is:

Method name (argument list) {method body}Copy the code

Among them:

Access modifiers: The range of permissions that a method is allowed to access. They can be public, protected, private, or even omitted, where public means that the method can be called by any other code

Return value type: the type of the value returned by the method. If the method does not return any value, the return value type is void. If the method has a return value, you need to specify the type of the return value and use a return statement in the method body to return the value

3. Method name: The name of the defined method, which must be a valid identifier

Parameter list: The list of parameters passed to the method. Multiple parameters can be separated by commas. Each parameter consists of parameter type and parameter name, separated by Spaces

Methods can be divided into four categories based on whether they take arguments and return values:

   Method with no parameters and no return value

If a method has no parameters and no return value, we call it a no-parameter, no-return method.

The method is used in two steps:

The first step is to define the method

For example, the following code defines a method called show, with no arguments and no return value, that executes “welcome to imooc.”

  

Note:

1. The method body is enclosed in a pair of curly braces to implement a specific operation

2. The method name is mainly used when calling this method. You need to pay attention to the naming conventions

The second step is to invoke the method

When you need to call a method to perform an operation, you create the object of the class and then pass the object name. The method name (); To implement the

For example, in the code below, we create an object called Hello and output information by calling the show() method on that object

  

The result is welcome to imooc.

Method with a return value without arguments

If a method contains no parameters but has a return value, we call it a no-parameter method with a return value.

For example, the following code defines a method called calSum, which takes no arguments but returns an int. It evaluates the sum of two numbers and returns the result

  

In the calSum() method, the return value is of type int, so you must use return to return an integer value in the method body

When calling a method with a return value, note that since the method returns a result after execution, the return value is generally received and processed when calling a method with a return value. Here it is: line 6

  

The result is: The sum of the two numbers is: 17

Pitfalls not to be ignored:

Void (); void ();

  

2. A method can return a maximum of one value, not multiple values

  

3. The type of the value returned by a method must be compatible. For example, if the return type is int, a String value cannot be returned

  

Method with no return value

Sometimes the execution of a method depends on certain conditions; in other words, additional information needs to be provided for a method to accomplish a particular function.

For example, in real life electric rice cooker can achieve the function of “cooking”, but the premise is that we must provide ingredients, if we don’t provide anything, it is really “even a clever housewife can’t cook a meal without rice”.

We can receive incoming data by adding a list of parameters to the method, which can be any primitive or reference type data.

Let’s start with a method that takes arguments but returns no value:

 

The above code defines a show method with a parameter name that outputs a welcome message.

The syntax for calling a parameterized method is similar to that for calling a no-parameter method, but the actual parameter values must be passed in when the call is made

  

Such as:

The running result is: Welcome, north travel!

Most of the time, we call the parameters of the method parameters. The purpose is to define the number and type of parameters that the method needs to pass in. The arguments to which the method is called are called arguments, which are the values passed to the method that are actually processed.

Problems that must not be ignored:

1. When calling a method with parameters, ensure that the number, type, and order of the arguments correspond to the parameters 1-1

  

When calling a method, the argument does not need to specify a data type, as in [].

3. The arguments to a method can be primitive data types, such as int, double, etc., or reference data types, such as String, array, etc

At line 10, the array.toString () method converts an Array to a string output

4. If there are multiple method parameters, separate them with commas

 Parameter return value method

If the method contains both parameters and return values, we call it a parameter-and-return method.

Such as:

The following code defines a show method that takes name and returns a String

  

Call a method with an argument and a return value:

The running result is: Welcome, north travel!

Java object oriented

object-oriented

Object Oriented is a new programming method, or a new programming specification. Its basic idea is to use the basic concepts of Object, class, inheritance, encapsulation, polymorphism and so on to design programs. The software system is constructed from the objects that exist objectively in the real world, and the natural thinking mode of human beings is used as far as possible in the system construction.

object

Object is an entity used to describe objective things in the system, and it is a basic unit of the system. An object consists of a set of properties and a set of services that operate on that set of properties.

Class instantiation generates objects. The life cycle of an object consists of three phases: generation, use, and elimination.

When there is no reference to an object, the object becomes a useless object. Java’s garbage collector automatically scans the dynamic memory area of objects, collecting and releasing unreferenced objects as garbage. When the System runs out of memory or garbage collection is called to system.gc (), the garbage collection thread runs synchronously with the System.

class

A class is a set of objects with the same attributes and methods. It provides a unified abstract description for all objects belonging to the class, including two main parts of attributes and methods. In an object-oriented programming language, a class is an independent program unit that should have a class name and include two main parts, properties and methods.

Class implementation in Java consists of two parts: the class declaration and the class body.

Class declaration

[the public] [the abstract | final] class className [extends superclassName] [implements interfaceNameList] {... }Copy the code

ClassName is the name of the class, superclassName is the name of the class’s parent class, and interfaceNameList is the list of interfaces implemented by the class.

The class body

class className{ [public | protected | private ] [static] [final] [transient] [volatile] type variableName; / / member variables [public | protected | private] [static] [final | the abstract] [native] [synchronized] returnType MethodName ([paramList]) [throws exceptionList]{statements}// Member methods}Copy the code

Member variable qualifier meaning:

  • Static: a class variable
  • Final: constants; Transient: transient variable used for archiving objects and serialization of objects
  • Volatile: Contribution variables that are shared by concurrent threads

Method implementation also includes two parts: method declaration and method body.

Method statement

Definition of qualifiers in method declarations:

  • Static: Class method, which can be called directly by the class name
  • Abstract methods have no method body
  • Final: Methods cannot be overridden
  • Native: code that integrates with other languages
  • Synchronized: controls the access of multiple concurrent threads

Method declarations include the method name, return type, and external parameters. The types of parameters can be simple data types or compound data types (also known as reference data types). For simple data types, Java implements value passing, with methods receiving the values of parameters but not changing the values of those parameters. If you want to change the value of a parameter, you use a reference data type, because the reference data type passes the method the memory address of the data, and operations on the data in the method can change the value of the data.

Method body

The method body is the implementation of the method, which includes declarations of local variables and all legal Java instructions. The scope of local variables declared in the method body is inside the method. If a local variable has the same name as a member variable of the class, the member variable of the class is hidden. To distinguish parameters from class member variables, we must use this. This is used to refer to the current object in a method whose value is the object on which the method was called. The return value must be identical to the return type, identical to it, or a subclass of it. When the return type is an interface, the return value must implement that interface.

A constructor

  • Constructor is a special method. Each class in Java has a constructor that initializes an object of that class.
  • The constructor has the same name as the class name and does not return any data type.
  • Overloading is often used in constructors.
  • Constructors can only be called by the new operator

Basic features of object orientation

encapsulation

Encapsulation is to hide the internal details of the object as much as possible and form a boundary with the outside world, reserving only limited interfaces and methods to interact with the outside world. The principle of encapsulation is to prevent external parts from accessing and manipulating the internal attributes of the object so as to avoid external damage to the internal attributes of the object.

You can set certain access permissions to the members of the class to realize the information hiding of the members of the class.

  • Private: a member of a class that is restricted to private and can only be accessed by the class itself. If the constructor of a class is declared private, other classes cannot generate an instance of that class.
  • Default: Unqualified members of a class are in the default access state and can be accessed by the class itself and classes in the same package.
  • Protected: Members of a class that are protected can be accessed by the class itself, its subclasses (including subclasses in the same package and in different packages), and all other classes in the same package.
  • Public: a member of a class that is qualified to public and is accessible by all classes.

inheritance

An object of a subclass has all the attributes and methods of its parent class. This is called inheritance from a subclass to a parent class.

  • In Java, a parent class can have more than one child class, but a child class can only inherit from one parent class, known as single inheritance.
  • Inheritance enables the reuse of code.
  • All classes in Java are derived directly or indirectly from the Java.lang. Object class.
  • Subclasses cannot inherit private access member variables and methods from their parent class.
  • Subclasses can override methods of the parent class by naming member variables with the same name as the parent class.

In Java, access to superclass members is achieved through super, which refers to the parent class of the current object. Super can be used in three ways:

  • Access hidden member variables of the parent class, such as super.variable;
  • Method([paramList]). Super () calls the constructor of the superclass.
  • Call the parent constructor, such as super([paramList]);

polymorphism

Object polymorphism means that attributes or methods defined in a parent class can have different data types or exhibit different behaviors after being inherited by subclasses. This makes the same property or method have different semantics in its parent class and its subclasses. For example, the “drawing” method of “geometry”, “ellipse” and “polygon” are both subclasses of “geometry”, and their “drawing” method has different functions.

Java polymorphism is manifested in two aspects: static polymorphism implemented by method overloading (compile-time polymorphism) and dynamic polymorphism implemented by method rewriting (runtime polymorphism).

  • Compile-time polymorphism: At compile time, the compiler statically determines which overloaded method to call based on its arguments.
  • Runtime polymorphism: A subclass object can be used as a superclass object because it inherits all of its parent’s attributes (except private ones). Wherever a parent object is used in a program, a subclass object can be used instead. An object can call a subclass’s method by referring to an instance of a subclass.

Overloading

  • Method overloading is a way for classes to handle different data types in a uniform way.
  • Multiple methods can be created in a class with the same name, but with different parameters and different definitions. Methods are called to determine which method to use depending on the number and type of arguments passed to them.
  • The return value type can be the same or different, so the return type cannot be used to distinguish overloaded functions.

Overriding.

  • A subclass rewrites a method of a parent class. We say that a method in a subclass can be Overriding if it has the same method name, return type, and parameter list as its parent.
  • If you want a method existing in the parent class, you can use the super keyword, which references the parent class of the current class.
  • A subclass function cannot have lower access modifier rights than its parent.

Java collection

Origin of sets

In general, our program needs to know how many objects to create based on when the program is running. But until the program runs and develops, we don’t know exactly how many objects we need, or even the exact type. To meet these general programming needs, we want to be able to create any number of objects at any time, anywhere. What will hold these objects? Arrays come to mind first, but arrays can only hold data of a uniform type, and their length is fixed. What then? The assembly was born!

What is a set?

The Java collection class, housed in the java.util package, is a container for holding objects.

A collection can only hold objects. For example, if you store an int 1 in a collection, it is automatically converted to an Integer class and stored there. In Java, each primitive type has a reference type.

Collections store references to multiple objects, and the objects themselves are stored in heap memory.

③ The set can store different types and unlimited number of data types.

Java collection framework diagram

This figure comes from:Blog.csdn.net/u010887744/…

A larger image access

Note that all of the above collection classes, except for the collection in the map family, implement the Iterator interface, which is an interface for iterating over the elements in the collection. The main methods are hashNext(),next(), and remove(). Its subinterface, ListIterator, adds three more methods to it, namely add(),previous(), and hasPrevious(). That is, if you implement an Iterator interface, the elements in the collection will only be iterated backwards, and the elements will not be iterated again. Unordered collections are usually implemented using this interface, such as HashSet. Collections of ordered elements typically implement the LinkedIterator interface, which can be traversed both through next() and through previous(), such as ArrayList.

Another feature is the use of abstract classes. If you have to implement a collection class yourself, it can be very cumbersome and workload to implement those abstract interfaces. This is where we can use abstract classes, which provide us with many

Off-the-shelf implementation, we just need to rewrite some methods or add some methods according to their own needs to implement the collection class, the workload is greatly reduced.

The collection,

Iterator: an Iterator that is the top-level interface to a Java collection (except the map collection).

Object Next () : Returns a reference to the element that the iterator just passed. The return value is Object, which needs to be cast to its desired type

Boolean hasNext() : Checks whether there are any more accessible elements in the container

Void remove() : Removes the element that the iterator just passed

So except for the map family of collections, we can iterate through the elements of the collection through iterators.

Note: We can trace the top-level interface of the Collection in the source code, such as the Collection interface, to see that it inherits the class Iterable

It would have to explain the difference between the Iterator and Iterable:

Iterable: exists in the java.lang package.

 

As you can see, it encapsulates the Iterator interface. So you can use iterators whenever you implement classes that implement the Iterable interface.

Iterator: exists in the java.util package. The core methods next(), hasNext (),remove().

Here we refer to an implementation of the Iterator class ArrayList to see how iterators are used: forget the List collection for the moment, just see how iterators are used

// Generates a List collection, typically implemented as an ArrayList. List list = new ArrayList(); // Add three elements list.add("Tom"); list.add("Bob"); list.add("Marry"); Iterator it = list.iterator(); While (it.hasnext ()){Object obj = it.next(); System.out.println(obj); }Copy the code

② Parent interface of Collection:List and Set

    

Take a look at an example use of the Collection:

ArrayList = new ArrayList(); // Add the element collection.add("Tom"); collection.add("Bob"); Remove ("Tom"); Collection c = new ArrayList(); c.add("Bob"); collection.removeAll(c); // Check if there is an element collection.contains("Tom"); // check whether collection.isempty () isEmpty; For (Object obj: Collection){system.out.println (obj); for(Object obj: collection){system.out.println (obj); Iterator Iterator = collection.iterator(); while(iterator.hasNext()){ Object obj = iterator.next(); System.out.println(obj); }Copy the code

Since the List interface inherits from the Collection interface, the basic approach is shown above.

1. Three typical implementations of the List interface:

List list1 = new ArrayList();

The bottom data structure is array, query fast, add and delete slow; Threads are unsafe and efficient

List list2 = new Vector();

The bottom data structure is array, query fast, add and delete slow; Thread-safe, inefficient, and almost obsolete this collection

③, List LinkedList() = new LinkedList();

The underlying data structure is linked list, query is slow, add and delete fast; Threads are unsafe and efficient

How do you remember it? We can imagine:

Arrays are like numbered people standing in a row. It’s easy to find the 10th person, and it’s easy to find the 10th person based on the number on the person. But insert, delete slowly, want to look at a certain position to insert or delete a person, the number of the person behind all want to change. Of course, people who join or delete are always at the end of the fast.

A list is like a circle of people holding hands. It’s not easy to find a tenth person. You have to count from the first person. But insert, delete fast. To insert, simply untie the hands of two people and rejoin the hands of the new person. Delete the same thing.

2. In addition to this, List traversal can also be performed using normal for loops, adding elements at specified locations, replacing elements, and so on.

ArrayList List = new ArrayList(); // Add three elements list.add("Tom"); list.add("Bob"); list.add("Marry"); Iterator it = list.iterator(); While (it.hasnext ()){Object obj = it.next(); //System.out.println(obj); } // Add the element list.add(2, 0) in the specified place; // Replace the element list.set(2, 1) in the specified place; Int I = list.indexof (1); System.out.println(" index: "+ I); For (int j=0; j<list.size(); j++){ System.out.println(list.get(j)); }Copy the code

A HashSet() is an unordered, non-repeatable collection

1, Set hashSet = new hashSet ();

The order of the elements in a HashSet cannot be guaranteed. Not repeatable; Not thread-safe; Collection elements can be NULL;

②, its bottom layer is actually an array, the meaning of existence is to speed up the query speed. We know that in general in the array, the index of the element in the array position are random, the elements of value and there is no definite relationship between the position of the element, therefore, to find specific values in the array, the need to find the value and compare a series of elements, the query efficiency is dependent on the search process is the number of times. There is a definite relationship between the index and value of the underlying array of HashSet: index=hash(value), so you can quickly find elements or indexes only by calling this formula.

For HashSet: If two objects return true via equals(), they should also have the same hashCode.

1. When storing an element in a HashSet, the HashSet first calls the object’s hashCode () method to get the object’s hashCode value, and then uses the hashCode value to determine where the object will be stored in the HashSet

1.1. If hashCode values are different, store the element directly in the location specified in hashCode()

1.2. If the hashCode value is the same, then the element is evaluated against equals() of the collection object

1.2.1 If hashCode is the same and equals is true, the same object is not stored in hashSet ()

1.2.2 If hashCode is equal to false and equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals If two objects return true via equals(), they should also have the same hashCode value.

Note: Each object stored in the hash table must provide an implementation of the hashCode() and equals() methods to determine if it is the same object

For the HashSet collection, we make sure that if two objects return true via equals(), they should have the same hashCode value.

Common hashCode() algorithms:

2, Set linkedHashSet = new linkedHashSet ();

①, can not be repeated, orderly

Because the bottom uses linked list and hash table algorithm. Linked lists guarantee the order in which elements are added, and hash tables guarantee the uniqueness of elements

3, Set treeSet = new treeSet ();

TreeSet: orderly; Non-repeatable, the bottom using red black tree algorithm, good at range query.

If you create a TreeSet object using the parameterless constructor of TreeSet(), you require that the classes of the elements you put into it implement the Comparable interface, so you cannot put null elements in it

You must place objects of the same class (sort by default) otherwise a cast exception may occur. We can restrict this by using generics

Set treeSet = new TreeSet(); treeSet.add(1); // Add data of type Integer treeset.add ("a"); // Add a String of data system.out.println (treeSet); // Type conversion exception is reportedCopy the code

  

Automatic sorting: When adding custom objects, you must implement the Comparable interface and override the compareTo(Object obj) method to customize the comparison rules

If this > obj, return a positive number of 1

If this < obj, return negative -1

If this = obj returns 0, the two objects are considered equal

* Two objects are compared in size and sorted in ascending order by the return value of the Comparable interface compareTo(Object obj) method

Custom sorting: When creating a TreeSet object, pass in the implementation class for the Comparator interface. Requirement: The return value of compare on the Comparator interface is the same as that of equals() on both elements

public class TreeSetTest { public static void main(String[] args) { Person p1 = new Person(1); Person p2 = new Person(2); Person p3 = new Person(3); Set<Person> set = new TreeSet<>(new Person()); set.add(p1); set.add(p2); set.add(p3); System.out.println(set); [1, 2, 3]}} class Person implements Comparator<Person>{public int age; public Person(){} public Person(int age){ this.age = age; } @override /*** ** / public int compare(Person o1, Person o1) Person o2) { // TODO Auto-generated method stub if(o1.age > o2.age){ return 1; }else if(o1.age < o2.age){ return -1; }else{ return 0; } } @Override public String toString() { // TODO Auto-generated method stub return ""+this.age; }}Copy the code

When you want to put an Object into a TreeSet and override the equals() method for that Object, you should ensure that the method has the same result as compareTo(Object obj)

Comparison of the implementation classes of the above three Set interfaces:

Common ground: 1. Elements are not allowed to be repeated

2, are not thread-safe classes, solution: Set the Set = Collections. SynchronizedSet object (Set)

Difference:

HashSet: The order of adding elements is not guaranteed, and the underlying hash table algorithm is used to query efficiently. To determine whether two elements are equal, equals() returns true and hashCode() is equal. That is, elements stored in a HashSet are required to override the equals() and hashCode() methods

LinkedHashSet: a subclass of HashSet. The underlying hash table algorithm and linked list algorithm are adopted to ensure the addition order of elements and query efficiency. But the overall performance is lower than that of HashSet

TreeSet: The order in which elements are added is not guaranteed, but the elements in the collection are sorted. The bottom layer adopts red-black tree algorithm (tree structure is more suitable for range query)

5, Map: key-value pair, key cannot be repeated, value can

1. Strictly speaking, Map is not a set, but a mapping between two sets.

2. The two sets can be regarded as a single piece of data without mapping relation. The Entry (key, value). A Map can be regarded as consisting of multiple entries.

3. Because the Map Collection is neither implemented in the Collection interface nor implemented in the Iterable interface, for-each traversal of the Map Collection is not possible.

Map<String,Object> hashMap = new HashMap<>(); // Add elements to Map hashmap. put("key1", "value1"); hashMap.put("key2", "value2"); hashMap.put("key3", "value3"); hashMap.put("key4", "value4"); hashMap.put("key5", "value5"); // Remove elements from the Map using the key value hashmap.remove ("key1"); Str1 = hashmap. get("key1"); Hashmap. put("key2", "change the Value of key2"); Collection<Object> value = hashmap.values (); for(Object obj : value){ //System.out.println(obj); } // Get a Set of keys from map.keySet(), then get(key) Value Set<String> Set = hashmap.keyset (); for(String str : set){ Object obj = hashMap.get(str); //System.out.println(str+"="+obj); Entrys = hashmap.entrySet (); entrys = hashmap.entrySet (); entrySet(); entrySet(); for(Map.Entry<String, Object> entry: entrys){ String key = entry.getKey(); Object value2 = entry.getValue(); System.out.println(key+"="+value2); } System.out.println(hashMap);Copy the code

Common implementation classes for Map:

⑥, Map and Set

1. There are several types of collections. HashMap and HashSet, both using hash table algorithms; TreeMap and TreeSet both adopt red-black tree algorithm. Both LinkedHashMap and LinkedHashSet employ hash table algorithms and red-black tree algorithms.

2, analysis of the underlying source of Set, we can see that Set is composed of Map Set Key.

 

Java IO streams

The concept and role of flow

  • Flow: Represents any data source object capable of producing or receiving data
  • The essence of streams is data transmission. Streams are abstracted into classes based on data transmission characteristics, facilitating more intuitive data operations.
  • Purpose: Establishes a transport channel for the data source and destination

The model adopted by JavaIO

  • Java’s IO model is well designed in that it uses the Decorator pattern to partition streams by function, and you can dynamically assemble these streams to get the functionality you need.
  • For example, if you need a buffered FileInputStream, you should use a combination of FileInputStream and BufferedInputStream.

I/O flow classification

  • Data flow is divided into input flow and output flow according to the direction of data flow

  • The input and output are relative to the code we wrote,

  • Input stream: Get resources from elsewhere (local files, resources on the network, etc.) to input into our program

  • Output stream: To output from our program to somewhere else (a local file), to save a string to a local file, we need to use the output stream.

  • It is divided into byte stream and character stream according to different processing data units

* 1 character = 2 bytes, 1 byte = 8 bits, 2 bytes of a Chinese character * Byte stream: Read (write) one byte at a time, when the resource file has Chinese characters, there will be garbled * character stream: When Chinese is present two bytes at a time, the stream is used to correctly transfer and display ChineseCopy the code
  • It can be divided into node flow and processing flow according to different functions

  • Node flow: To read and write data from or to a specific place (node). As a FileInputStream

  • Processing flow: Is the connection and encapsulation of an existing stream, through the encapsulated stream function calls to achieve data read and write. As a BufferedReader. Constructors that handle streams always take another stream object as an argument. A stream object is wrapped multiple times by other streams

  • There are four basic abstract flow types that all streams inherit from

  •   The input stream The output stream
    Byte stream InputStream outputStream
    Characters of the flow Reader Writer
* inputStream: byte inputStream *! [](https://upload-images.jianshu.io/upload_images/24923247-d6fd2455897f2261.png? ImageMogr2 /auto-orient/strip% 7cimageview2/2 /w/1240) * outputStream: byte outputStream *! [](https://upload-images.jianshu.io/upload_images/24923247-e98c91db7ba24779.png? ImageMogr2 /auto-orient/strip% 7cimageView2/2 /w/1240) * Reader: character input stream *! [](https://upload-images.jianshu.io/upload_images/24923247-1a0ca5b82e86def4.png? ImageMogr2 /auto-orient/strip% 7cimageView2/2 /w/1240) * Writer: character output streamCopy the code
  • Summarize the classification of flows

    1. The first thing you need to know is whether you want to choose an input stream or an output stream, and it depends on your situation, so if you want to write from the program to somewhere else, choose the output stream, and vice versa
    2. Then consider whether you want to use byte stream or character stream when transmitting data, i.e. 1 byte at a time or 2 bytes at a time
    3. The first two steps can select an appropriate node stream, such as byte inputStream inputStream, and if you want to enhance functionality from this, select an appropriate node stream in the processing stream
  • In Java, the Unicode standard is adopted for characters. A character is 16 bits, that is, a character is represented by two bytes. To do this, JAVA introduced streams that process characters. Because of different data encodings, there are stream objects that efficiently manipulate characters. The essence is based on the byte stream read, to check the specified code table

I/O stream characteristics

  1. First in, first out, data written to the output stream is read by the input stream first
  2. Sequential access, in which a string of bytes can be written one by one to the stream, and a string of bytes will be read in the order in which they are written, without random access to intermediate data. (RandomAccessFile can be accessed from anywhere in the file.)
  3. Read – only or write – only. A stream can be either an input stream or an output stream. The input stream can only be read and the output stream can only be written. In a data transfer channel, if data is to be written and read, two streams are provided

There are five classes of interfaces commonly used by IO streams

  • The most important things in the java.io package are five classes and one interface. The five classes are File, OutputStream, InputStream, Writer, and Reader. An interface refers to Serializable. Mastering the core operations of IO gives you an initial understanding of the IO architecture in Java.
* The main classes are as follows: 1. File (File characteristics and management) : File class is the object that encapsulates files and folders in the File system, and can operate files and folders with the idea of objects. Various metadata File save the File or directory information, including the File name, File size, last modified time, whether to read, access to the path of the current File name, whether the specified File exists, access to the current directory in the File list, create, and delete files and directories 2. InputStream (binary format) : Abstract classes, byte-based input operations, are the parent of all input streams. 3. OutputStream (binary format operation) : Abstract class. Byte-based output operations. Is the parent class of all output streams. Reader (file format operation) : abstract class, character-based input operation. Writer (file format operation) : abstract class, character-based output operation. A separate class that extends directly to Object. It is rich in functions, can be accessed from any location of the file (input/output) operations. [](https://upload-images.jianshu.io/upload_images/24923247-22e2ca9d9a58272f.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)Copy the code

Java IO stream objects

1. Enter the byte stream InputStream

  • Recognize the function of each class

  • ByteArrayInputStream: byte array input stream. The function of this class is to read in bytes from a byte array (byte[]), that is, to store the resource files in bytes into the byte array from which we retrieve them

  • PipedInputStream: pipe byte input stream, used with PipedOutputStream to implement pipe communication between multiple threads

  • FilterInputStream: decorator in decorator mode, which decorators inherit, so all subclasses of this class are used to decorate other streams, i.e. processing classes

  • BufferedInputStream: A buffered stream, embellished and enhanced with an internal buffer that holds bytes, instead of one or two bytes being sent each time the buffer is full. More efficient

  • DataInputStream: DataInputStream, which is used to decorate other input streams, “allowing applications to read basic Java data types from the underlying input stream in a machine-independent manner

  • FileInputSream: file input stream. It is usually used to read files

  • File: Operations are performed on files in a specified directory. For details, see the blog post on File. Note that this class, while under the IO package, does not inherit from the four base classes

  • ObjectInputStream: ObjectInputStream used to provide persistent storage of “basic data or objects”. In layman’s terms, the ability to transfer objects directly (used in deserialization)

2. Output an OutputStream

  • OutputStream is the parent class of all output byte streams. It is an abstract class

  • **ByteArrayOutputStream and FileOutputStream are two basic media streams that write data to Byte arrays and local files, respectively. **PipedOutputStream writes data to a pipe shared with other threads

  • ObjectOutputStream and all subclasses of FilterOutputStream are decorator streams (used in serialization)

3. Character input stream Reader

  • Reader is the parent of all input character streams. It is an abstract class

  • CharReader and StringReader are two basic media streams that read data from a Char array and a String, respectively. PipedReader reads data from pipes shared with other threads

  • BufferedReader is obviously a decorator, and it and its subclasses decorate other Reader objects

  • FilterReader is the parent of all custom concrete decorator streams. Its subclass, PushbackReader, decorates a Reader object by adding a line number

  • InputStreamReader is a bridge between a byte stream and a character stream that converts a byte stream into a character stream. FileReader is a common utility class that does this, and its source code clearly uses methods to convert FileInputStream into Reader. We can get some tricks out of this class. The Reader classes are used in the same way as InputStream classes. There’s a Reader and InputStream relationship

4. Character output stream Writer

  • Writer is the parent of all output character streams and is an abstract class

  • CharArrayWriter and StringWriter are two basic media streams that write data to Char arrays and Strings, respectively. PipedWriter writes data to a pipe shared with other threads

  • BufferedWriter is a decorator that provides buffering for writers

  • PrintWriter and PrintStream are very similar in function and usage

  • OutputStreamWriter is a bridge between OutputStream and Writer, and its subclass FileWriter is a concrete class that implements this function (see SourceCode). The functionality and usage are very similar to OutputStream

5. Byte stream and character stream usage :(critical)

  • Character stream and byte stream usage: Byte stream is generally used for processing images, videos, and PPT, Word type files. The character stream is used to process plain text files, such as TXT files. The byte stream can be used to process plain text files, but the character stream cannot be used to process non-text files, such as images and videos

Character stream and byte stream conversion

  • When a text file is stored as a byte stream on a hard disk, it is read by InputStreamReader and converted to a character stream for processing by the program. The character stream processed by the program is converted to a byte stream for saving by OutputStreamWriter

  • Characteristics of conversion flow:

    1. It is the bridge between character stream and byte stream
    2. Can read the byte data through the specified encoding into characters
    3. Can read the character data through the specified encoding into bytes
  • When to use a transformation flow?

    1. When there is a conversion action between byte and character
    2. Streams operate when data needs to be encoded or decoded
  • Concrete object representation

    • InputStreamReader:Byte to character bridge
    • OutputStreamWriter:Character to byte bridge
    • These two stream objects are members of the character system, they transform, and they are character streams themselves, so we need to pass in the byte stream object during construction
    • OutputStreamWriter(OutStreamout): Outputs the byte stream as a character stream
    • InputStreamReader(InputStream in) : Input the byte stream as a character stream

The difference between byte stream and character stream (emphasis)

  • The difference between byte stream and character stream:

    • The byte stream has no buffer and is output directly, whereas the character stream is output to the buffer. So while the byte stream is output without calling the colse() method, the character stream is output only when the close() method is called to close the buffer. To output information while the character stream is open, you need to call the flush() method manually
    • The read and write units are different: the byte stream is in bytes (8 bits), the character stream is in characters, and multiple bytes may be read at a time according to the code table mapping characters
    • Different objects: byte streams can handle all types of data (images, avi, etc.), whereas character streams can only handle character types of data
    • Conclusion: Character streams are preferred whenever dealing with plain text data. Everything else uses byte streams

IO support by the System class

  • For some frequent device interactions, the Java language system has three stream objects that can be used directly:

    • System.in (standard input), usually for keyboard input
    • System.out (standard output) : Usually written to the display
    • System.err (Standard error output) : Usually written to the monitor
  • Standard I/O

    • Java programs can exchange brief information with the outside world through command line parameters. It also specifies how to exchange information with standard input and output devices, such as keyboards and monitors. Through files, information can be exchanged in any form of data with the outside world

Processing flow BufferedReader BufferedWriter, BufferedInputStream

  • BufferedOutputsStream, all need to wrap up the node stream. A Buffered stream is also called a Buffered stream. A Buffered stream processes the input and output of a file the fastest. Therefore, buffered streams are often used

What is decorator pattern

  • In my own words, is added to a more features, and the first thing we think of inheritance, inheriting good meet our requirements, no matter how much you want to add the function of the layer, inherit the implementation of the layers can be used, but it poses a problem, as soon as I need to change my needs, I will need to change something in the source code, And a class in the inheritance chain make some changes, it is not about our ideas of design patterns, so there will be a decorator pattern, decorators have been decorator instance, then what is the specific decoration is another we write a class to inherit the decorator, when we need the decoration, to new out of the class, then it is decorator as parameters passed in

  • Now look at a concrete example. For example, if we need to make a chicken drumstick, what is the process

    1. We start with the basic ingredients, which are two pieces of bread, which you need for any burger, right
    2. What kind of burger you make depends on what ingredients you put in it, like lettuce, chicken, etc., so it depends on the ingredients, what kind of burger you want to make
    3. Isn’t it much more convenient to use decorator mode after all the materials have been added and just calculate the price? Change a burger, also do not need to change the source code, do not need anything, I hope you can understand the idea
  • The processing flow is a concrete decorator, and the node flow is the decorator

Scanner class

  • Java 5 has added the java.util.Scanner class, a new utility for scanning incoming text. It’s sort of a combination of the previous StringTokenizer and Matcher classes. Because any data must be retrieved through the capture group of the same schema or through the use of an index to retrieve various parts of the text. You can then use a combination of regular expressions and methods to retrieve specific types of data items from the input stream. Thus, in addition to using regular expressions, the Scanner class can analyze arbitrary strings and data of primitive types such as int and double. With Scanner, you can write a custom parser for any text content you want to process

  • Scanner Socket stream or character stream:

    • Scanner socket: Scanner(InputStream) in the Scanner constructor, InputStream always gets the stream interface you want as long as it is properly socket
    • Readable. you will need to use the new Java SE5 interface Readable, which stands for “something that has a read() method.” Looking at the Readable interface API you will find that almost all of the classes you want with Reader will be there

serialization

  • Object data stored in memory is converted to binary data stream for transmission, and any object can be serialized

  • Implementation method: implement java.io.Serializable interface

  • To write a Java object to a hard disk or transfer it to another computer on the network, we need to convert the corresponding object to a byte stream using Java. For this general operation, why don’t we use a uniform format? Yes, this is where the concept of Java serialization comes in. The objectOutput-stream subclass of Java OutputStream has the corresponding WriteObject(Object Object), which requires that the corresponding Object implements the Java serialization interface

  • When tomcat is used to develop JavaEE related projects, objects in the corresponding session are stored on the hard disk after tomcat is closed. If we want to be able to read the contents in the corresponding session from Tomcat when Tomcat is restarted, The content stored in the session must be serialized, and the JDBC loading driver uses deserialization to turn the string into an object

deserialization

  • Converts binary data back to the original object

  • Structure:

  • ObjectInputStream (InputStream in)

  • Methods:

  • Object readObject() reads objects from ObjectInputStream

  • Transient keyword (certain attributes of a class do not need to be serialized)

  • The above serialization and deserialization realized the object serialization, but it can be found that the operation is to serialize all the attributes of the whole object, so the TRANSIENT keyword can be defined by the transient keyword without saving some content

    Private TRANSIENT String title;

    The title property cannot be serialized

summary

  • The inputStream class’s lack of functionality is addressed by Scanner
  • The OutputStream class’s shortcomings are addressed by PrintStream
  • The Reader class’s lack of functionality is addressed by BufferReader
  • The Writer class’s lack of functionality is addressed by PrintWriter
  • PrintStream for output, Scanner for printwriter for read and bufferReader for read

Java threads, exceptions and network programming

I’m not going to write about threads and network programming, because I don’t have enough space to write a sentence or two about threads and network programming, so I’ll write a separate article about threads and network programming if I have time.

Java Architect Learning Core book list

Title: One-sentence evaluation
Java Core Technology Needless to say, one of the most influential and valuable books in the Java field
Ideas for Java Programming This one needs no introduction. It’s a timeless classic
The Art of Concurrent Programming in Java Domestic authors write concurrent Java books, relatively simple and easy to understand, widely circulated Java thread state changes map from this book
In-depth Understanding of the Java Virtual Machine JVM, this one is enough
“Effective Java” Known as the Magic Book of Java Programming Ideas, it explains how to write robust, efficient code, although some development experience is required.
Spring In Action Spring Introduction classic book
Spring Revealed The book is older, but the concept and principle is very clear, after reading, look at the source code of Spring5 is also very good
Spring Boot 2.x Read a lot of SpringBoot books, personal feeling this is good, more detailed, comprehensive
MyBatis Technology Insider MyBatis source code analysis of the book is not many, recommend this, combined with the source code to read better
Data Structure and Algorithm Analysis Foreign data structure and algorithm analysis of the classic textbook, the content is comprehensive, rigorous and strict
Computer Network I can’t help but recommend a textbook, which is comprehensive and systematic, but may not be friendly to non-koji players
Illustrated HTTP This need not introduce more, very vivid explain HTTP protocol book, read more friendly
Understanding Computer Systems in Depth A well-reviewed book on computer operating systems, but the black book can be difficult to read
SQL Must Know must Know Very popular MySQL primer, can also be used as a reference book
High Performance MySQL MySQL domain classic, advanced must see
Redis Development and Operation From the development, operation and maintenance of two aspects of Redis combat experience, in-depth analysis of the underlying implementation, including large-scale cluster development and operation and maintenance of actual cases
Redis Design and Implementation Redis Advanced Classic books
SpringCloud Micro-service Combat Nice SpringCloud book
Spring Cloud Alibaba Micro Service Principle and Practice Some components of Netflex are in maintenance, Spring Cloud Alibaba is popular recently (technology changes really fast), there are not many books on this topic, this one is relatively recommended
RabbitMQ Field Guide Simple and clear RabbitMQ technical book
The Definitive Guide to Kafka There are plenty of great Kafka books out there. Here’s a guide to Kafka
RocketMQ Field and Principles RocketMQ is short on books, but this one is a good primer and a little thin on principles

In addition to the main categories listed above, here are some more.

  • Container recommended “Docker from Starter to Event” “Kubernetes authoritative Guide”;

  • Maven recommends Maven In Action;

  • Git recommends ProGit;

  • Linux is, of course, Birdman’s Linux home dish;

  • Elasticsearch: Elasticsearch

  • Design Patterns recommends Zen of Design Patterns.

I’ve collected all of the above recommended books in electronic files, which you can click on for your student party or cash-strapped friends

  • 22 Java Architect Core books

I’ll leave it there, the hair is falling out, and it would be great to get a like and a follow. See you in the next article

end