current position:Home>[90 details that Java programmers must know and know] 1. Java algorithm Baidu online disk

[90 details that Java programmers must know and know] 1. Java algorithm Baidu online disk

2022-01-26 21:35:09 m0_ fifty-four million eight hundred and sixty-one thousand fou

It has only a single parameter , Returns a corresponding instance of this type .

Date date = Date.from(instant);

2、of, Polymerization methods

With multiple parameters , Returns an instance of this type , Combine them .

Set faceCards = EnumSet.of(JACK,QUEEN,KING);

3、valueOf

Than from and of A more cumbersome alternative .

BigInteger prime = BigInteger.valueOf(Integer.MAX_VALUE);

4、instance perhaps getInstance, The returned instance is described by the parameters of the method .

StackWalker luke = StackWalker.getInstance(options);

5、create perhaps newInstance, and instance and getInstance equally , but create and newInstance To ensure that each call returns a new instance .

Object newArray = Array.newInstance(classObject,arrayLen);

6、getType, image getInstance equally , But when factory methods are in different classes .Type Represents the type of object returned by the factory method .

FileStore fs = Files.getFileStore(path);

7、newType, image newInstance equally .

8、type,getType and newType A short version of

Four 、 summary


In short , Both static factory methods and common constructors have their own advantages , We need to understand their respective strengths .

The static factory approach is more appropriate , Therefore, the first reaction is to provide public constructors , Regardless of the static factory .

The first 2 strip : Consider using a builder when you encounter multiple constructor parameters

======================

Static factories and constructors have a common limitation : None of them can be well extended to a large number of optional parameters .

1、 Overlapping constructors


Overlapping constructors work , But when there are many parameters , Client side code can be hard to write and hard to read .

2、JavaBeans Pattern


First call the parameterless constructor to create the object , And then call setter Method to set each necessary parameter .

JavaBeans Pattern is my common way , however JavaBeans It also has serious shortcomings . Because the construction process is divided into several calls , In the process of construction JavaBean May be in an inconsistent state . Class cannot guarantee consistency by verifying the validity of constructor parameters .

3、 Builder pattern ( Not the builder pattern in the design pattern )


Fortunately, , There's a third alternative . It can be like the security of overlapping constructor pattern , And it's guaranteed to look like JavaBeans Readability like patterns . This is the builder model .

package com.guor.effective.chapter2.worker;

public class Worker {

private int id;

private String name;

private int age;

private int sex;

private String school;

private String address;

public static class Builder{

private int id;

private String name;

private int age = 18;

private int sex = 1;

private String school = “ Liaoning University of petroleum and chemical technology ”;

private String address = “ Dalian hi tech park, Liaoning Province ”;

public Builder(int id, String name) {

this.id = id;

this.name = name;

}

public Builder age(int val){

age = val;

return this;

}

public Builder sex(int val){

sex = val;

return this;

}

public Builder school(String val){

school = val;

return this;

}

public Builder address(String val){

address = val;

return this;

}

public Worker build() {

return new Worker(this);

}

}

public Worker(Builder builder){

int id = builder.id;

String name = builder.name;

int age = builder.age;

int sex = builder.sex;

String school = builder.school;

String address = builder.address;

}

@Override

public String toString() {

return “Worker{” +

“id=” + id +

“, name=’” + name + ‘’’ +

“, age=” + age +

“, sex=” + sex +

“, school=’” + school + ‘’’ +

“, address=’” + address + ‘’’ +

‘}’;

}

}

package com.guor.effective.chapter2.worker;

public class Test {

public static void main(String[] args) {

Worker worker = new Worker

.Builder(1,“ Guo Xiaotong ”).age(1).sex(1).school(“ China Railway Nord kindergarten ”)

.address(“ China Railway Nord Binhai garden ”).build();

System.out.println(worker.toString());

}

}

The first 3 strip : Enforce with private constructors or enumeration types Singleton attribute

=============================

The first 4 strip : Enhance the non instantiation capability through private constructors

======================

package com.guor.effective.chapter2.test;

public class Test2 {

private Test2(){

System.out.println(“ I am a private constructor ”);

}

public static void constructor() {

System.out.println(“ I am a tool class ”);

}

}

The first 5 strip : Preference is given to dependency injection to reference resources

=================

The first 6 strip : Avoid creating unnecessary objects

==============

1、 Automatic boxing


Method for creating redundant objects , One is called automatic packing , It allows programmers to mix basic types with encapsulated types , Automatic packing and unpacking as required . Automatic boxing blurs the difference between the basic type and the basic type of Boxing , But it doesn't completely eliminate , There are subtle semantic differences between them , There are also obvious differences in performance .

Illustrate with examples , Calculate all int The sum of positive integer values .

(1) Basic type performance test

package com.guor.effective.chapter2.test;

public class getIntSum {

public static void main(String[] args) {

long a= System.currentTimeMillis();// Get current system time ( millisecond )

long sum = 0;

for (int i = 0; i < Integer.MAX_VALUE; i++) {

sum += i;

}

System.out.println(“int Sum of positive integers :”+sum);

System.out.println(“ Program execution time is :”+(System.currentTimeMillis()-a)+“ millisecond ”);

}

}

(2) Package type performance test

Long Than long The time difference is still quite great . Give priority to basic types , Not the encapsulation type , Be careful of automatic packing .

2、 Create meaningful small objects


Don't mistakenly assume that what this article introduces implies “ Creating objects is very expensive , We should create objects as much as possible ”. contrary , Because the constructor of small objects only does a small amount of display work , So the creation and recycling of small objects is very cheap , Especially in modern times JVM This is even more true . Improve program clarity by creating additional objects 、 Conciseness 、 Functionality , This is usually a good thing . conversely , Avoid creating objects by maintaining your own object pool , It's not a good practice , Unless the objects in the pool are very heavyweight , A typical example of using object pools correctly is the database connection pool . The cost of establishing a database connection is very expensive , So it makes sense to reuse these objects . generally speaking , Maintain your own object pool , It usually makes the code messy , At the same time, increase the memory usage , And it can damage performance . modern JVM Implement a highly optimized garbage collector , Its performance will easily exceed that of the lightweight object pool .

The first 7 strip : Eliminate outdated object references

=============

1、 Manage memory by yourself


As long as the class manages its own memory , Programmers should be alert to memory leaks . Once the element is released , Any object references contained in this element should be cleared .

2、 Another common source of memory leaks is caching .


Once you put the object in the cache , It may be forgotten , Stay in cache for a long time . For this question , have access to WeakHashMap For caching , When an item in the cache expires , They are automatically deleted . Remember that only when the life cycle of the desired cache item is determined by the external reference of the key, not by the value ,WeakHashMap It's useful .

3、 The third source of memory leaks is listeners and other callbacks


If you implement a API, The client is here API Register callback in , But not explicitly unregister , So unless you do something , Otherwise, they'll keep piling up . The best way to ensure that callbacks are immediately treated as garbage collected is to save only their weak references , for example , Just save them as WeakHashMap The key .

Due to memory leakage, it will not behave as

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing

Apparent failure , So they can exist in a system for many years . Often by examining the code carefully , Or with the help of Heap Profiling tools (Heap Profiler) To find out the memory leak . therefore , If you can know how to predict such problems before a memory leak occurs , And stop them from happening , That's the best .

The first 8 strip : Avoid using termination methods and elimination methods

=================

copyright notice
author[m0_ fifty-four million eight hundred and sixty-one thousand fou],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262135078858.html

Random recommended