37-Java Basic Class Library

Java Basic Class Library

StringBuffer class

  The String class is a functional class that will be used in all project development, and this class has the following characteristics:

  • Each string constant belongs to an anonymous object of the String class and cannot be changed;
  • String has two constant pools: static constant pool and runtime constant pool;
  • String object instantiation is recommended to be completed in the form of direct assignment, so that the object can be directly saved in the object pool for reuse next time;

  Although the String class is easy to use, serious thinking will reveal its biggest drawback: the content is not allowed to be modified, so in order to solve this problem, the StringBuffer class is specially provided to implement string content modification processing.
  The StringBuffer class does not have two object instantiation methods like the String class. The StringBuffer class must be instantiated to the ordinary class object first, and then the method can be called for processing.

  • Construction method: public StringBuffer(String str)/();
  • Data append: public StringBuffer append (data type variable);

Compared

package per.lyz.StringBuffer_study;

public class JavaClassDemo {
    
    
	public static void main(String[] args) {
    
    
		String str = "hello";
		StringBuffer str_1 = new StringBuffer("hello");
		change(str);
		str_1.append("world");
		System.out.println(str);
		System.out.println(str_1.toString());
	}
	public static void change(String temp) {
    
    
		temp += "world";
	}
}

In practice, the content of the string rarely changes, and this change is not aimed at the change of the static constant pool.
example

String strA = "www.mldn.cn";
String strB = "www." + "mldn" + ".cn";
strA == strB (True)

At this time, the content of strB is not considered a change, or more strictly speaking, for strB when the program is compiled, it will become the following form:
str.append("www.").append("mldn").append(".cn");
all "+" after compilation become the append() method in StringBuffer, in In the program, the StringBuffer and String classes can be directly converted to each other

  • String objects can be transformed into StringBugffer by relying on the constructor method of the StringBuffer class or using the append() method;
  • All class objects become String type through the toString() method;

  In addition to supporting the modification of the string content, the StringBuffer class actually provides some methods that the String class does not have:

  • Insert data: public StringBuffer insert(int offset, data type b);buf.append(".cn").insert(0,"www").insert(4,"mldn");
  • Delete data in the specified range: public StringBuffer delete(int start,int end);
  • Reverse string content: public StringBuffer reverse();

In fact, a functional class similar to the StringBuffer class: StringBuilder class (JDK1.5), the methods provided by this class are the same as those provided by StringBuffer, but the biggest difference is that the methods in the StringBuffer class are thread-safe and all use the synchronized key Characters are marked, and the StringBuilder class is non-thread-safe.

Interview: Explain the difference between String, StringBuffer, StringBulider?

  • String class is the preferred type of string, the biggest feature is that the content cannot be changed;
  • The contents of StringBuilder and StringBuffer classes are allowed to be modified;
  • StringBuffer (JDK1.0) is thread-safe, while StringBuilder (JDK1.5) class is non-thread-safe.

CharSequence interface

  CharSequence is an interface that describes string results. Once again, three common subclasses can be found in the interface:

  • String class:public final class String extends Object implements Serializable,Comparable<String>,CharSequence
  • StringBuffer class:public final class StringBuffer extends Object implements Serializable,CharSequence
  • StringBuilder class:public final class StringBuilder extends Object implements Serializable,CharSequence

rGNKzV.png
Now as long as there is a string, it can be instantiated for the CharSequence interface;
CharSequence str = "test!"; //子类实例像父接口转型

  CharSequence itself is an interface, and the following operation methods are also defined in the interface,

  • Get the specified index character: public char charAt(int index);
  • Get the length of the string: public int length();
  • Intercept part of the string: public CharSequence subSequence(int start, int end);
public class JavaClassDemo {
    
    
	public static void main(String[] args) {
    
    
		CharSequence str = "www.mldn.cn";
		CharSequence sub = str.subSequence(4, 8);
		System.out.println(sub);
	}
}

See that CharSequence describes a string.

AutoCloseable interface

  AutoCloseable is mainly used in the processing of resource development in the future to realize the automatic closing (release) of resources. For example, in the future file, network, and database development, due to the limited server resources, the resources must be closed after use before they can be updated. Multi-user use;
example: In order to better explain the resource problem, it is completed by sending and processing a message

interface IMessage{
    
    
	public void send();		//消息发送
}
class NetMessage implements IMessage{
    
    
	private String msg;
	public NetMessage(String msg) {
    
    
		this.msg = msg;
	}
	public boolean open() {
    
    		//获取资源链接
		System.out.println("获取消息发送连接资源");
		return true;
	}
	public void close() {
    
    
		System.out.println("关闭连接,释放资源");
	}
	@Override
	public void send() {
    
    
		if(this.open()) {
    
    
			System.out.println("发送消息" + this.msg);
		}
		
	}
	
}
public class JavaClassDemo {
    
    
	public static void main(String[] args) {
    
    
		NetMessage ns = new NetMessage("test");
		ns.send();
		ns.close();
	}
}

Since all resources need to be closed after processing, you can implement aAutomatic shutdownTherefore, the AutoCloseable access interface was introduced. This interface was provided in JDK1.7 and has only one method:

  • Closing method:public void close() throws Exception;

rJCVF1.png
  In order to achieve automatic closing processing, in addition to using AutoCloseable, you also needCombined with exception handling statementcarry out.
Realize automatic closing processing

interface IMessage extends AutoCloseable{
    
    
	public void send();		//消息发送
}
class NetMessage implements IMessage{
    
    
	private String msg;
	public NetMessage(String msg) {
    
    
		this.msg = msg;
	}
	public boolean open() {
    
    		//获取资源链接
		System.out.println("获取消息发送连接资源");
		return true;
	}
	public void close() throws Exception {
    
    
		System.out.println("关闭连接,释放资源");
	}
	@Override
	public void send() {
    
    
		if(this.open()) {
    
    
			System.out.println("发送消息" + this.msg);
		}
	}
}

public class JavaClassDemo {
    
    
	public static void main(String[] args) throws Exception{
    
    
		try (IMessage nm = new NetMessage("test")){
    
    
			nm.send();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

In the subsequent chapters, we will come into contact with the problem of closing resources, and we will often see the use of the AutoCloseable interface.

Runtime class

  Runtime describes the state of the runtime. In the entire JVM, the Runtime class is the only class related to the running state of the JVM, and an instantiated object of this class is provided by default.
  Since only one Runtime class object is allowed to be provided in each JVM process, the construction method of this class is privatized, and the singleton design pattern is used, and the singleton design pattern must provide a static method to obtain this class instance . Because the Runtime class belongs to the singleton design pattern, if you want to obtain an instantiated object, you can rely on the method in the class to obtain:
rJF57Q.png

  • Get instantiated object:public static Runtime getRuntime();
  • Number of available processes:public int availableProcessors();

Get Runtime class object

public class Runtime_study {
    
    
	public static void main(String[] args) {
    
    
		Runtime run = Runtime.getRuntime();
		System.out.println(run.availableProcessors());		//获取CPU内核数,
	}
}

The following important operation methods are also provided:

  • Get the maximum available memory space: public long maxMemory();(The default configuration is 1/4 of the local system memory)
  • Get the available memory space: public long totalMemory();(The default configuration is 1/64 of the native system memory)
  • Get free memory space:public long freeMemory();
  • Manual GC processing:public void gc();

Interview: What is GC? How to deal with

  • The GC (Garbage Collector) garbage collector is a garbage release function that can be automatically called by the system, or manually called by gc() in the Runtime class.

System class

Method of definition:

  • Array copy:public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
  • Get the current date and time value:public static long currentTimeMillis();
  • Perform garbage collection:public static void gc();

The gc method uses gc processing in Runtime.

Cleaner class

  Cleaner is an object cleaning operation provided after JDK1.9, and its main function is to replace the finialize() method. There are two special functions in C++: constructor and destructor (object manual recycling). In Java, all garbage space is automatically reclaimed by GC, so in most cases there is no need to use destructor. Because of this, all Java does not provide this support.
  However, Java still provides the user with the finishing operation. Before each instantiated object is recycled, it at least gives him a breathing space. The method of initializing the object finishing is the finalize() method provided in the Object class: @Deprecated(since='9') protected void finalizer() throws Exception;
the biggest feature of this method. Throwable exception type is thrown. This exception type is divided into two subtypes: Error and Exception, which are usually handled by Exception.
Observe traditional recycling

class Member{
    
    
	public Member() {
    
    
		System.out.println("构造方法");
	}
	@Override
	protected void finalize() throws Throwable {
    
    
		System.out.println("析构方法");
		throw new Exception("暂时不销毁");
	}
}
public class CleanerStudy {
    
    
	public static void main(String[] args) {
    
    
		Member mem = new Member();
		mem = null;		//成为垃圾
		System.gc();
	}
}

Starting from JDK1.9, this operation is not recommended. For the recovery and release of objects, starting from JDK1.9, developers are recommended to use AutoCloseable or java.lang.ref.Cleaner class (Cleaner also supports AutoCloseable processing) for recovery processing.

import java.lang.ref.Cleaner;

class Member implements Runnable{
    
    
	public Member() {
    
    
		System.out.println("构造方法");
	}
	@Override
	public void run() {
    
    		//清除对象
		System.out.println("析构对象");
	}
}
class MemberCleanning implements AutoCloseable{
    
    		//实现清除处理
	private static final Cleaner cleaner = Cleaner.create();		//创建一个清除处理
	private Member member;
	private Cleaner.Cleanable cleanable;
	public MemberCleanning() {
    
    
		this.member = new Member();		//创建新对象
		this.cleanable = this.cleaner.register(this, this.member);		//注册使用对象
	}
	@Override
	public void close() throws Exception {
    
    
		// TODO Auto-generated method stub
		this.cleanable.clean();		//启动多线程
	}		//实现清除处理
	
}

public class CleanerStudy {
    
    
	public static void main(String[] args) throws Exception {
    
    
		try(MemberCleanning mc = new MemberCleanning()){
    
    
			;
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

In the new generation of cleaning and recycling processing, the use of multithreading is considered in more cases, that is, in order to prevent possible delays in processing, the processing before the recycling of many objects is completed by a single thread.

Object cloning

  The so-called object cloning refers to the object object, and it is a brand new copy. Use the existing object content to create a new object, using the clone() method in the Object class;
protected Object clone() throws CloneNotSupportedException;
  all classes inherit the Object parent class by default, so all Classes must have a clone() method, but not all classes want to be cloned, so the object must be cloned first. Then the class where the object is located must implement a Cloneable interface. This interface does not have any method to provide, because heDescribes an ability.
Implement object cloning

class Members_1 implements Cloneable{
    
    
	private String name;
	private int age;
	public Members_1(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
    
    
		return super.toString()+"Member [name=" + name + ", age=" + age + "]";
	}
	@Override
	protected Object clone() throws CloneNotSupportedException {
    
    
		// TODO Auto-generated method stub
		return super.clone();		//调用父类中提供的clone()方法
	}
}
public class CloneStudy {
    
    
	public static void main(String[] args) throws CloneNotSupportedException {
    
    
		Members_1 memberA = new Members_1("lyz", 18);
		Members_1 memberB = (Members_1)memberA.clone();
		System.out.println(memberA);
		System.out.println(memberB);
	}
}

The need for object cloning seldom arises due to not very special requirements in development.

Guess you like

Origin blog.csdn.net/MARVEL_3000/article/details/111567545