Java Basics 20, class loaders

“This is the 20th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

About the author

  • The authors introduce

πŸ“ blog home page: author’s home page πŸ“ Introduction: JAVA quality creator πŸ₯‡, a junior student πŸŽ“, participated in various provincial and national competitions during school, and won a series of honors


Class set

Meet class set

If you want to save more than one object, must use an array of objects, but the object array itself have a biggest problem is to determine the length of the data, so list to deal with the completed the development of dynamic array of objects, but the list of development difficulty is very big, and if a linked list to really to use, only rely on the written before is not enough, Some code tuning is also required.

And after JDK1.2 formally introduced the concept of class Set, class Set is a dynamic array of objects, belongs to each data structure implementation class, in the whole class is the main composition of some core operation interface: Collection, List, Set, Map, the Iterator, Enumeration.

Collection interface

Collection is the parent interface that holds the largest amount of a single Collection. The definition of the Collection interface is as follows:

public interface Collection<E> extends 可迭代<E>
Copy the code

The direct benefit of adding generic applications to the Collection interface since JDK1.5 is to avoid classcastExceptions, where all data should be saved of the same type. Common methods for this class are as follows:

Method names type describe
public boolean add(E e) ordinary Add data to the collection
boolean addAll(Collection<? extends E> c) ordinary Add a set of data to the collection
public void clear() ordinary Clearing collection data
public boolean contains(Object o) ordinary Query whether data exists
public Boolean isEmpty() ordinary Determines whether the collection has elements
public Iterator iterator() ordinary Gets an Iterator interface object for output
public boolean remove(Object o) ordinary To delete data, you need the equals() method
public int size() ordinary Gets the length of the set
public Object[] toArray() ordinary Returns the collection data

In development, the add() and iterator() methods are heavily used, and the other methods are barely used. An interface is a standard for storing data and does not distinguish between storage types. For example, if you want to store data, you may need to distinguish between duplicates and non-duplicates. Therefore, in actual development, it is often considered to use the subinterfaces of the Collection interface: List (allow repetition), Set (do not allow repetition).

List Interface Introduction

List is one of the most commonly used subinterfaces of a Collection and allows duplicate subinterfaces.

Method names type describe
public E get(int index) ordinary Gets the data at the specified index location
public E set(int index,E element) ordinary Modifies the data on the specified index
public ListIterator listIterator() ordinary Instantiate the ListIterator interface

The main feature of the List subinterface compared to the Collection interface is that it has a get() method to retrieve content by index. But List itself belongs to one of our interfaces, and to get an instantiated object of the interface you must subclass it. There are three common subclasses of List: ArrayList, Vector, and LinkedList.

The final operation should still be based on the interface, so since it is going to be based on the interface, all methods should refer to the definition of the interface.

ArrayList subclass

ArrayList is an implementation of array operations on the List interface.

List basic operations

package com.day17.demo;

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args) {
		List<String> all = new ArrayList<>();// Only String data can be stored in the set
		System.out.println(all.size() + "" + all.isEmpty());
		all.add("Hello");
		all.add("Hello");	// Duplicate data
		all.add("world~!");
		all.add("zsr~");
		System.out.println(all.contains("zsr~"));
		System.out.println(all.contains("zsr")); System.out.println(all); }}Copy the code

With our code we can verify that List allows duplicate data to be saved.

The List contains a get() method, which can be used in conjunction with the index to retrieve data.

List’s get() method

package com.day17.demo;

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args) {
		List<String> all = new ArrayList<>();// Only String data can be stored in the set
		all.add("Hello");
		all.add("Hello");	// Duplicate data
		all.add("world~!");
		all.add("zsr~");
		for (int i = 0; i < all.size(); i++) { System.out.println(all.get(i)); }}}Copy the code

But remember that the get() method is a List subinterface. If you use a Collection instead of a List, you can only fetch the Collection as an array of objects.

(generally not used in development)Collection for output processing and fetching data

package com.day17.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class CollectionDemo {
	public static void main(String[] args) {
		Collection<String> all = new ArrayList<>();// Only String data can be stored in the set
		all.add("Hello");
		all.add("Hello");	// Duplicate data
		all.add("world~!");
		all.add("zsr~");
		// If the operation returns as Object, it may need to be cast downward, which may cause a ClassCastException
		Object result [] = all.toArray();// Changes to an Object arraySystem.out.println(Arrays.toString(result)); }}Copy the code

Collection and simple Java classes

In real development, the most commonly held data types in collections are simple Java classes.

Save a simple Java class to the collection

package com.day17.demo;

import java.util.ArrayList;
import java.util.List;

class Person{
	private String name;
	private Integer age;
	public Person(String name, Integer age) {
		super(a);this.name = name;
		this.age = age;
	}
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge(a) {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public boolean equals(Object obj) {
		// TODO Auto-generated method stub
		if(this == obj){
			return true;
		}
		if (obj == null) {return false;
		}
		if(! (objinstanceof Person)){
			return false;
		}
		Person per = (Person) obj;// The object itself can be transformed downward
		return this.name.equals(per.name) && this.age.equals(per.age);
	}
	@Override
	public String toString(a) {
		return "Person [name=" + name + ", age=" + age + "]"; }}public class ListDemo {
	public static void main(String[] args) {
		List<Person> all = new ArrayList<>();
		all.add(new Person("Zhang".10));
		all.add(new Person("Bill".21));
		all.add(new Person("Fifty".19));
		// Equals () must be supported for the remove() and contains() methods
		all.remove(new Person("Bill".21));
		System.out.println(all.contains(new Person("Bill".21)));
		for (int i = 0; i < all.size(); i++) { System.out.println(all.get(i)); }}}Copy the code

The List collection must be supported by equals() if it uses the remove(), contains() methods. The use in simple Java classes is rarely used.

The Vector subclass

Vector is the older subclass, which is deprecated from JDK1.0 and ArrayList is deprecated from JDK1.2.

package com.day17.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class ArrayListDemo {
	public static void main(String[] args) {
		List<String> all = new Vector<>();// Only String data can be stored in the set
		all.add("Hello");
		all.add("Hello");	// Duplicate data
		all.add("world~!");
		all.add("zsr~");
		for (int i = 0; i < all.size(); i++) { System.out.println(all.get(i)); }}}Copy the code

Interview question: Explain the difference between ArrayList and Vector?

The difference between ArrayList Vector
History of time JDK1.2 JDK1.0
Processing form Asynchronous processing, higher form Synchronization deteriorates performance
Data security Non-thread-safe Thread safety
The output form Iterator, ListIterator, foreach Iterator, ListIterator, foreach, Enumeration

LinkedList subclass

There is also a LinkedList subclass within the List interface, which will use the same form as before if it is converted to our parent interface.

package com.day17.demo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args) {
		List<String> all = new LinkedList<>();// Only String data can be stored in the set
		all.add("Hello");
		all.add("Hello");	// Duplicate data
		all.add("world~!");
		all.add("zsr~");
		for (int i = 0; i < all.size(); i++) { System.out.println(all.get(i)); }}}Copy the code

Interview question: Explain the difference between ArrayList and LinkedList?

The difference between ArrayList LinkedList
A constructor public ArrayList() {

this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;

}
public LinkedList() {

}
Open up the length of the Open up the size of fixed length Dynamic opening
Time complexity The time complexity is 1 The time complexity is n

ClassLoader ClassLoader

The Class Class describes the entire information of the Class. The forName() method provided in the Class Class can handle only loading through the path configured by the CLASSPATH. Our Class loading path could be network, file, or database. This is the main purpose of the ClassLoader class.

Learn about class loaders

First Class observe a method: public ClassLoader getClassLoader();

Write a simple reflection program to observe the existence of a ClassLoader

package com.day17.demo;
class Member{// Custom classes must be in the CLASSPATH
	
}
public class TestDemo1 {
	public static void main(String[] args) {
		Class<?> cls = Member.class;
		System.out.println(cls.getClassLoader());
		System.out.println(cls.getClassLoader().getParent());
		System.out.println(cls.getClassLoader().getParent().getParent());
	}
}

/*
sun.misc.Launcher$AppClassLoader@73d16e93
sun.misc.Launcher$ExtClassLoader@15db9742
null
*/
Copy the code

There are two loaders, AppClassLoader(application class loader) and ExtClassLoader(extended class loader).

In addition to CLASSPATH, there is actually a loading directory in Java: C: ProgramFiles Java jdk1.8.0_241 jre lib ext

Looking at the class, we see a method in the ClassLoader: public <? > loadClass(String name) throws ClassNotFoundException to load classes.

The custom this

Implements the file class loader

package com.day17.demo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

class MyClassLoader extends ClassLoader{
	/** * implements a custom class loader that, after passing in the class name, loads * from the specified file path@param className
	 * @return
	 * @throws Exception
	 */
	publicClass<? > loadData(String className)throws Exception{
		byte classDate [] = this.loadClassData();
		return super.defineClass(className, classDate, 0, classDate.length);
		
	}
	/** * Load the file of the class by specifying the file path, for binary reading *@return
	 * @throws Exception
	 */
	private byte [] loadClassData() throws Exception{
		InputStream input = new FileInputStream("f:" + File.separator + "java" + File.separator + "Member.class");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte [] data = new byte [20];// Define the buffer to read
		int temp = 0;
		while((temp = input.read(data)) ! = -1){
			bos.write(data,0,temp);
		}
		byte ret [] = bos.toByteArray();
		input.close();
		bos.close();
		returnret; }}public class ClassLoaderDemo {
	public static void main(String[] args) throws Exception{ Class<? > cls =new MyClassLoader().loadData("com.day17.test.Member"); System.out.println(cls.newInstance()); }}Copy the code

One of the biggest benefits of class loaders for our users is the ability to load classes through dynamic paths.