java foundation -- clutter

Array subscript out of bounds exception:

1. Array subscript out of bounds exception: ArrayIndexOutOfBoundsException

2. Null pointer exception: NullPointerException

Three characteristics of object oriented

Encapsulation inheritance polymorphism

Overloading of methods: two are the same and different, two are the same class and method name, and one is the different parameter list.

1. Same class
2. Same method name
3. Different list

Method Rewriting: 2 is the same as 2, small and 1 is large. 2 is the same means that the method name is the same and the formal parameter list is the same; 2. Small means that the return value type is the same or smaller, and the exception thrown is smaller; 1. The access rights are the same or greater.

1. Same method name
2. The formal parameter list must be the same
3. The return value type is the same or smaller
4. Throw exception smaller
5. Same or greater access rights
Note: if the method type of the parent class is void, the method type of the child class must only be void. Static methods cannot be overridden. Only non static methods can be overridden.

Formal parameters and arguments: a formal parameter is a parameter that has not been assigned, and an argument is a parameter that has been assigned.

//The variable number parameter can only declare one deformable parameter at most. If it is to be used, it can be used with other variables, and the variable parameter needs to be placed at the tail
public void show(String ... str){

}


public void show(int a,String ... str){

}

Value Passing Mechanism of method parameters

If the variable is a basic data type, the value assigned at this time is the data value saved by the variable.

If the variable is a reference data type, the variable is the address value of the data saved by the variable

java is value passing

Stack and heap

2.5 storage contents in heap and stack
Stack: when a function is called, the next instruction in the main function (the next instruction in the function call statement) is the first one on the stack
The address of the execution statement), and then the parameters of the function. In most C compilers, the parameters are stacked from right to left
, followed by local variables in the function. Note that static variables are not stacked.
When this function call is over, the local variable comes out of the stack first, then the parameter, and finally the pointer at the top of the stack points to the place where it is stored at the beginning
Address, that is, the next instruction in the main function, from which the program continues to run.
Heap: generally, one byte is used at the head of the heap to store the size of the heap. The specific contents of the heap are arranged by the programmer. Generally, new structures, objects, and arrays

Recursion of method

Is a method body that calls itself

Embodiment of encapsulation

Just like calling the get and set methods in the bean, but setting the property to private is to prevent users from directly using the property to assign values to them. For example, if you want to give some restrictions on this property, for example, int a > 100, you need to implement it through the set method.

constructor

Constructor is equivalent to a method. When new is used, it can be understood that new is a constructor. The constructor calls by default:

person a = new person();

//This constructor is provided by default
public void person(){
//It is empty by default
};

explain

  1. If there is no constructor of the definition class displayed, the system will provide an empty parameter constructor by default
  2. Defines the format of the constructor: permission modifier class name (formal parameter list) {}
  3. Multiple constructors are defined in a class, which constitute overloads with each other
  4. Once we show that the class constructor is defined, the system no longer provides the default null parameter constructor
  5. There will be at least one constructor in a class

JavaBean

  • JavaBean is a reusable component written in the Java language
  • The so-called javaBean is a java class that meets the following standards
    1. Class is public; 2. There is a public constructor without parameters; 3. There are attributes and corresponding get and set methods

Is equivalent to the existence of entity classes

Design pattern of MVC

mvc is divided into three layers: view model layer, controller layer and data model layer

The model layer mainly processes data

  • Data object encapsulation
  • Database operation class
  • database

The control layer controller handles business logic

  • Application interface related
  • Store fragment
  • Display list adapter
  • Service related
  • Extracted base class

View layer view display data

  • Related tools
  • Custom view

Polymorphism

What is polymorphism

It can be understood that a thing has many forms.
Object polymorphism: the reference of the parent class points to the object of the child class (or the reference assigned to the parent class by the object of the child class)

Use of polymorphism, virtual method call

With object polymorphism, we can only call the methods declared in the parent class at compile time, but at run time, we actually execute the methods of the child class overriding the parent class.
Summary: see the left for compilation and the right for operation

Prerequisites for polymorphic use

① Class inheritance relationship;
② Method rewriting;

For example, the following is an example of polymorphism

Person p1 = new Person();
p1.eat();

Person p2 = new Man();
p2.eat();

The method called by p1 will be the method in the Person class, while the method called by p2 will be the method in the Man class, which is only a method that can be overridden.
For example, there is a run() method in Man, but not in the Person class. p2 can use this method, but p1 can't. This is the compiler. Look at the left.
The polymorphism of methods does not look at attributes. It only applies to methods, not attributes.

instanceof keyword usage

a instanceof A: judge whether object a is an instance of class A. If yes, return true; If not, false is returned.

Usage scenario: in order to avoid the exception of ClassCastException during the downward transformation, we first judge the instanceof before the downward transformation. Once true is returned, the downward transformation will be carried out. If false is returned, no downward transition will be performed.
If a instanceof A returns true, a instanceof B also returns true, where class B is the parent of class A.

finalize() method

finalize() is a method in Object. When an Object in heap space is not pointed to by stack space variables, the Object will wait to be recycled by java: This is implemented in jdk:

protected void finalize() throws Throwable { }
}

equals() method (toString() method is also overridden in each subclass)

  1. Is a method, not an operator
  2. Applies only to reference data types
  3. The method of calling equals in the class of Object is the same as using = =, the following subclasses rewrite its methods, such as String, Date, and so on.
//This is the method of equals in the Object class
    public boolean equals(Object obj) {
        return (this == obj);
    }

****************************************

//This is the method of equals in String
public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

The difference between equals and = =:
==Is to compare addresses directly, while equals is to compare characters

static keyword usage

When using static to modify attributes
Instance variable: we have created multiple objects of the class, and each object independently has a set of non static properties in the class. When modifying a non static attribute in one object, it will not affect the modification of the same attribute value in other objects
Static variable: we create multiple objects of the class, and multiple objects share the same static variable. When a static variable is modified through an object, it will cause other objects to call the static variable, and the modified variable will be called.

be careful:
① Static variables will be loaded with the loading of the class, and can be called in the way of "class. Static variables"
② Static variables are loaded before objects are created
③ Since the class will only be loaded once, only one copy of the static variable will exist in memory and in the static field of the method area

Persin.name="aa"

example: name Property is a static property staic name
Person a1=new Person();
a1.name="Xiao Hong"

Person a2=new Person();
a2.name="Xiao Ming"

sout(a1.name);
//The output will be Xiao Ming

Static modifier static method

1. Static variables will be loaded with class loading, and can be called in the way of "class. Static variables";
2. In static methods, only static methods or attributes can be used; In non static methods, you can call both non static methods or attributes and static methods or attributes;
3. this keyword and super keyword cannot be used in static methods.

public void eat(){
sout("Eat something");
}

public staic void run(){
sout("run");
//eat(); It cannot be called, and an error will be reported;
}

In development, how to determine whether a method or attribute should be declared as static?
······Attributes: attributes can be shared by multiple objects and will not vary with different objects. For example, bank interest rate, fractional line, etc
······Method: the method of operating static attributes, usually set to static; Methods in tool classes are traditionally declared as static, such as Math, Arrays

Singleton mode: http://blog.csdn.net/dmk877/article/details/50311791 (Rev.)

(1) Privatize the constructor of this class
(2) Create a class object in this class through new
(3) Define a public method to return the object created in this class

Hungry Han style
Advantage: threads are safe
Disadvantages: the object loading time is too long

public class Singleton {
 
	private static Singleton instance=new Singleton();
	private Singleton(){};
	public static Singleton getInstance(){
		return instance;
	}
}

//Access mode
Singleton instance = Singleton.getInstance();

Lazy style
Advantage: delay object creation
Disadvantages: thread unsafe

public class Singleton {
 
	private static Singleton instance=null;
	
	private Singleton() {};
	
	public static Singleton getInstance(){
		
		if(instance==null){
			instance=new Singleton();
		}
		return instance;
	}
}

Static and non static code blocks

Static code block:
① There can be output statements inside
② Executes as the class loads, and only once
③ Function: initialize some class information

Non static code block:
① There can be output statements inside
② Each time an object is created, a non static block of code is executed
③ Function: you can initialize the properties of an object when creating an object

③ Function: initialize the properties of some classes

package test;

public class StaticTest2 {
	//Create a static code block
	static{
		System.out.println("Static code blocks are executed");
	}
	//Create a non static code block
	
	{
		System.out.println("Non static code block executed");
	}
	//Create a construction method
	StaticTest2(){
		System.out.println("Construction method");
	}
	
}

What are the common methods in String?

Text connection

final keyword

Final final
Used to decorate a class: this class cannot be inherited by other classes. Such as String class, System class, etc.
Used to decorate a method: this method can no longer be overridden.
Used to modify a variable: at this time, the "variable" is called a constant
Used to modify attributes: you can consider explicit initialization, initialization in code block and initialization in constructor.
Used to modify a local variable: indicates that this formal parameter is a constant. When we call this method, we assign an argument to the constant formal parameter. Once assigned, we can only use this argument in this method body, but we can't re assign it.
static final: used to modify attributes and global constants.

abstract class

abstract modifier class:
····This class cannot be instantiated (that is, it cannot be new)
····There must be a constructor in the abstract class to be called when subclass instantiation (involving the whole process of subclass object instantiation)

abstract modification method:
····Only the method declaration, no method body;
····Abstract classes can create abstract methods. The class containing abstract methods must be an abstract class;
····Subclasses can be instantiated only after overriding all abstract methods in the parent class;

Anonymous inner class: connect

Interface

····Constructor cannot be defined in interface! This means that the interface cannot be instantiated
····In Java development, the interface is used by allowing the class to implement. If the implementation class covers all the abstract methods in the interface, the implementation class can be instantiated. If the implementation class does not cover all the abstract methods in the interface, the implementation class is still an abstract class.
····Java classes can implement multiple interfaces - > making up for the limitations of Java stand-alone programs
····The interface is equivalent to a 100% abstract class, which is composed of global constants and abstract methods.

Difference between interface and abstract class:
Abstract class:
Construction method: there are construction methods for subclass instantiation.
Member variable: it can be a variable or a constant.
Member methods: can be abstract or non abstract.
Interface:
Construction method: no construction method
Member variable: can only be constant. Default modifier: public static final
Member method: jdk1 7 can only be abstract. Default modifier: public abstract (recommended: Please always give the default modifier manually)
jdk1.8. You can write specific methods starting with default and static

Inner class

Classification of internal classes: member internal classes (static, non static) vs local internal classes (within methods, code blocks, constructors)

public class test04(){
   		//Member inner class     
        class Dog{
            
        }
        
        public void method(){
        //Partial inner class
            class AA{
                  }
        }
    }

In String:
1. The splicing result of constants and constants is in the constant pool, and the same content constants will not exist in the constant pool;
2. As long as there is one variable, the result is in the heap;
3. If the result of splicing calls the intern() method, the return value is in the constant pool.

Comparable interface

Implement the Comparable interface, which can be used to rewrite the compareTo method for user-defined sorting order.

public class DateTimeTest implements Comparable{


    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

Comparator interface

Implement the Comparator interface, which can be used to customize sorting

public class DateTimeTest implements Comparator {


    @Override
    public int compare(Object o1, Object o2) {
        return 0;
    }
}

Enumeration class: Deepen understanding

Use of enumeration classes:
1. The understanding of enumerating classes: there are only a limited number of objects in a class, which can be determined. We call this class enumeration class
2. Enumeration classes are strongly recommended when you need to define a set of constants
3. If there is only one object in the enumeration class, it can be used as an implementation of singleton mode

How to define enumeration classes?
Method 1: jdk5 Custom enumeration class before 0
Mode 2: jdk5 After 0, you can use the emun keyword to define enumeration classes

Enumeration type is a new feature in Java 5. It is a special data type. The reason why it is special is that it is not only a class type, but also has more special constraints than class types. However, the existence of these constraints also makes enumeration types concise, safe and convenient.

When there are no enumerated classes:

    public class DayDemo {
        public static final int MONDAY =1;
        public static final int TUESDAY=2;
        public static final int WEDNESDAY=3;
        public static final int THURSDAY=4;
        public static final int FRIDAY=5;
        public static final int SATURDAY=6;
        public static final int SUNDAY=7;
    }

The following is defined using enum

    enum Day {
        MONDAY, TUESDAY, WEDNESDAY,
        THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }

Method used:

    public class EnumDemo {
        public static void main(String[] args){
            //Direct reference
            Day day =Day.MONDAY;
        }
    }

java collection overview

Let's talk about the characteristics of arrays:
1. Once initialized, its length is determined
2. Once the array is defined, the type of its elements is determined. We can only operate the data of the specified element, such as String[] arr, int[] arr1;
Disadvantages of arrays in storing multiple data:
1. Once initialized, its length cannot be modified and its flexibility is poor.
2. The methods provided in the array are very limited. It is very inconvenient and inefficient to add, delete and insert data.
3. Get the number of actual elements in the array. There are no ready-made properties or methods available in the array.
4. The characteristics of array data storage: orderly and repeatable, which can not meet the requirements of disorder and non repeatable

java collection framework

Collection interface: single column collection, used to store objects one by one.
······List interface: stores ordered and repeatable data. ArrayList, LinkedList, etc
······Set interface: stores unordered and non repeatable data. HashSet,LinkedHashSet,TreeSet

Map interface: a two column set used to store a pair of key value data. HashMap, LinkedHashMap, Treemap, etc

Collection interface When adding data obj to the object of the implementation class of, the class where obj is located is required to override equals().
Colletion connection II

Iterator iterator

Iterator is an object that can traverse a Collection, provides a common operation interface for various containers, and isolates the traversal operation of containers from the underlying implementation, so as to decouple. It is mainly used for the Collection interface.

 @Test
    void test03(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);

        Iterator iterator = coll.iterator();

        //Mode 1
        System.out.println(iterator.next());

        //Method 2: recommendation
        //hasNext(): judge whether there is another element
        while (iterator.hasNext()){
            //next(): ① move the pointer down ② return the elements at the collection position after moving down
            System.out.println(iterator.next());
        }

        //Error mode 1
        //iterator. Each time next () calls this method, the pointer moves down one bit. So the output content is 456,false. An error NoSuchElementException will be reported
        while (iterator.next()!=null){
            System.out.println(iterator.next());
        }

        //Error mode 2
        //Every time you use the iterator() method to get a new iterator object for the collection object, the default cursor is before the first element of the collection.
        while (coll.iterator().hasNext()){
            System.out.println(coll.iterator().next());
        }
        //remove method of iterator
        while (iterator.hasNext()){
            Object obj=iterator.next();
            if (obj.equals("Tom")){
                iterator.remove();
            }
        }
    }

foreach loop to traverse the collection

 @Test
 public void test04(){
     Collection coll = new ArrayList();
     coll.add(123);
     coll.add(456);
     coll.add(new String("Tom"));
     coll.add(false);

     //For (type local variable of collection element: collection object), the iterator is still used internally
     for(Object obj:coll){
         System.out.println(obj);
     }

 }

List interface

ArrayList: as the main implementation class of the List interface; Thread is not safe, but it is efficient; Use the underlying Object [] to store elementData;
LinkedList: for frequent insert and delete operations, the efficiency of using this class is higher than that of ArrayList; The bottom layer uses double linked list storage;
Vector: as an ancient implementation class of the List interface; Threads are safe, but inefficient;

Interview question: what are the similarities and differences among ArrayList, LinkedList and Vector?
Same: the three classes implement the List interface, and the characteristics of storing data are the same: storing orderly and repeatable data
Difference: see above

Common methods for ArrayList collections
Three traversal methods: ① Iterator iterator mode; ② Enhanced for loop; ③ Ordinary way;

@Test
    public void test05(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(456);

        System.out.println(list);
        list.add(1,"bb");
        System.out.println(list);

        List list1 = Arrays.asList(1, 2, 3);
        list.addAll(list1);
        System.out.println(list.size());

        //Returns the first occurrence of the element in the collection
        int i = list.indexOf(456);
        System.out.println(i);

        //Removes the element at the specified index location and returns this element
        Object remove = list.remove(0);
        System.out.println(remove);
        System.out.println(list);
        
        //Set the specified index location element to xx
        list.set(1,"CC");
        System.out.println(list);

        //Returns the subset from fromIndex to toIndex. The interval is left closed and right open
        List subList = list.subList(2, 4);
        System.out.println(subList);
        System.out.println(list);

    }

Set interface

HashSet: as the implementation class of Set; Thread unsafe; null values can be stored
LinkedHashSet: as a subclass of HashSet; When traversing the internal data of the device, it can be traversed in the order of addition;
TreeSet: you can sort by specifying the attributes of the added object

  1. There are no new methods defined in the Set interface, but all the methods declared in the Collection are used;
  2. For objects stored in the Set container, the corresponding classes must override the equals() and hashCode(Object obj) methods to implement the object equality rule. That is, "equal objects must have equal hash codes".

Understand that Set stores unordered and non repeatable data:
Take HashSet as an example:
1. Disorder: not equal to randomness. The stored data is not added in the order of array index in the top-level array, but determined according to the hash value of the data;
2. Non repeatability: ensure that when the added element is judged according to equals(), it cannot return true. That is, only one same element can be added.
·····Add element process: we add element a to the HashSet. First, we call the hashCode() method of the class where element a is located to calculate the hash value of element a, and then calculate the hash value of element a through some algorithm
·········The storage position (i.e. index position) in the underlying array of HashSet to judge whether there are elements in this position of the array:
······If there are no other elements in this position, element a is added successfully ------------ case 1.
······If there are other elements b (or multiple elements in the form of a linked list) at this position, compare the hash values of element a and element b;
······If the hash values are different, element a is added successfully -------------- case 2.
If the hash values are the same, you need to call the equals() method where element a is located:
·····equals() returns true, element a addition failed
·····equals() returns false, element a is added successfully --------- > case 3.
·For cases 2 and 3 where the addition is successful, element a and the data already existing at the specified index position are stored in a linked list.

    /*
    LinkedHashSet As a subclass of HashSet, while adding data, each data also maintains two references to record the previous data and the next data of this data.
    Advantages: LinkedHashSet is more efficient than HashSet for frequent traversal operations
   */


    /*
    1.The data added to TreeSet must be objects of the same class.
    2.There are two sorting methods: natural sorting (implementing Comparable interface) and custom sorting (comparator interface).
    3.In natural sorting, the criteria for comparing whether two objects are the same is: compareTo() returns 0, not equals().
    4.In custom sorting, the criteria for comparing whether two objects are the same is: compare() returns 0 instead of equals()
    */

    @Test
    public void test06(){
        Comparator com =new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return 0;
            }
        };

        TreeSet set = new TreeSet();
        set.add(123);
        set.add(456);
        set.add(129);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

Program results:

Map interface

Map: double column data, which stores the data of key value pairs
····HashMap: as the main implementation class of Map; Unsafe thread and high thread efficiency; Store null key and value
·······LinkedHashMap: ensure that the map elements can be traversed in the order of addition.
····Reason: Based on the original HashMap underlying structure, a pair of pointers are added to point to the previous and subsequent elements. For frequent traversal operations, this kind of execution is more efficient than HashMap.
·····TreeMap: ensure sorting according to the added key value to realize sorting traversal. At this time, consider the natural sorting or customized sorting of keys. Red and black trees are used at the bottom.
·····Hashtable: as an ancient implementation class; Thread safety and low efficiency; null key and value cannot be stored
·····Properties: commonly used to handle configuration files. Both key and value are of type String

 /*
    HashMap Bottom layer of: array + connection (jdk7 before)
                 Array + linked list + red black tree (jdk8)

    Map Keys in: unordered and non repeatable. Use Set to store all keys ----- > the class where the key is located should override equals() and hasCode() (take HashMap as an example)
    Map Values in: unordered and repeatable. Use Collection to store all values
    A key value pair: key value constitutes an Entry object
    Map Entries in: unordered and non repeatable. Use Set to store all entries

    HashMap The underlying implementation principle of? (jdk 7)
    map.put(key1,value1)
    First, call hashCode() of the class where key1 is located to calculate the hash value of key1. After the hash value is calculated by some algorithm, the position stored in the Entry array is obtained.
        If the data in this location is empty, key1-value1 is added successfully!
        If the data is not empty, (which means that there are one or more data in this location (in the form of linked list)), compare the hash values of key1 and one or more existing data:
            If the hash value of key1 is different from the hash value of existing data, key1-value1 is added successfully!
            If the hash value of key1 is the same as that of an existing data (key2-value2), continue the comparison: call the equals(key2) method of the class where key1 is located:
                If equals() returns false: key1-value1 is added successfully!
                If equals() returns true: value1 replaces value2.

    During the continuous addition process, the problem of capacity expansion will be involved. When the critical value is exceeded (and the location to be stored is not empty), the default capacity expansion method is to expand the capacity to twice the original capacity and copy the original data.

    jdk8 Compared with jdk7 in the underlying implementation:
    1.new HashMap(): The bottom layer does not create an array with a length of 16;
    2.jdk 8 The underlying array is: Node [], not entry [];
    3.When the put() method is called for the first time, the underlying layer creates an array with a length of 16;
    4.jdk 7 Underlying structure: array + linked list. jdk 8 underlying structure: array + linked list + red black tree. When the number of data in the form of linked list of elements at an index position of the array is > 8
    When the length of the current array is > 64, all data at the index position is stored in red black tree.
    */

    @Test
    public void test08(){

        Map map = new HashMap();
        //add to
        map.put("AA",123);
        map.put(45,123);
        map.put("BB",56);
        //modify
        map.put("AA",87);

        System.out.println(map);

        HashMap map1 = new HashMap();
        map1.put("CC",123);
        map1.put("DD",123);

        map.putAll(map1);
        System.out.println(map);

        //remove(Object key)
        Object cc = map.remove("CC");
        System.out.println(cc);
        System.out.println(map);

        //Empty map
     /*   map.clear();
        System.out.println(map.size());*/

        //Gets the value of the specified key
        System.out.println(map.get(45));

        //Does containsKe (Object value) contain the specified value
        boolean isExist = map.containsKey("BB");
        System.out.println(isExist);

        boolean b = map.containsValue(123);
        System.out.println(b);

        //Judge whether it is empty
        System.out.println(map.isEmpty());

        //Traverse all key sets, keySet()
        Set set = map.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        System.out.println("========================================================");
        //Traverse all value sets: values()
        Collection values = map.values();
        for (Object obj:values){
            System.out.println(obj);
        }
        System.out.println("-----------");

        //Traverse all key value: entryset()
        Set entrySet = map.entrySet();
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()){
            Object obj = iterator1.next();
            //All elements in the entry set collection are entries
            Map.Entry entry =(Map.Entry)obj;
            System.out.println(entry.getKey()+"---"+entry.getValue());
        }
    }

Collections tool class

  /*
    Collections:Tool classes for operating Collection and Map
    */
    @Test
    public void test09(){
        List list = new ArrayList();
        list.add(123);
        list.add(12);
        list.add(33);
        list.add(33);
        list.add(33);
        list.add(33);
        list.add(13);
        list.add(0);

        System.out.println(list);

        //Reverse order
        Collections.reverse(list);
        System.out.println(list);

        //Randomization sequence
        Collections.shuffle(list);
        System.out.println(list);

        //Natural sorting
        Collections.sort(list);
        System.out.println(list);

        //Position exchange
        Collections.swap(list,1,2);
        System.out.println(list);

        //The number of occurrences of the query element
        int frequency = Collections.frequency(list, 33);
        System.out.println(frequency);

        System.out.println("=================");
        List dest = new ArrayList();

        //The length cannot be less than the length of the copied array
        dest.add(123);
        dest.add(123);
        dest.add(123);
        dest.add(123);
        dest.add(123);
        dest.add(123);
        dest.add(123);
        dest.add(123);
        dest.add(123);

        List dest1 = Arrays.asList(new Object[list.size()]);
        System.out.println(dest.size());
        Collections.copy(dest,list);

        System.out.println(dest);

        //Multiple synchronizedXXX() methods are provided in the Collections class, which can wrap the specified collection into a thread synchronized collection to
        //It can solve the thread safety problem when multithreading accesses collections concurrently

        //The list1 returned is the thread safe object
        List list1 = Collections.synchronizedList(list);


    }

generic paradigm

Generic content details

Role of generics

Early Object types can accept any Object type, but in practical use, there will be the problem of type conversion. This hidden danger exists, so Java provides generics to solve this security problem.

You cannot use generic classes in static methods or exceptions
Class A is the parent of class B, but g < a > and G < b > do not have a child parent relationship, and they are juxtaposed.

Use of wildcards:?

Class A is the parent class of class B. g < a > and G < b > have no relationship. Their common parent class is g <? >.

IO stream

Use of File class

Definition: Java file classes represent file names and directory pathnames in an abstract way. This class is mainly used to create files and directories, find files and delete files.

1. An object of file class represents a file or a file directory (commonly known as folder)
2. The file class is declared in Java Under IO package
3. The file class involves the creation, deletion, renaming, modification time, file size and other methods of files or file directories, and does not involve the operation of writing or reading file contents. If you need to read or write file contents, you must use IO stream to complete.
4. Objects of subsequent File classes are often passed to the stream constructor as parameters, indicating the "end point" of reading or writing

We create a file object through the file constructor (the constructor only creates an instance of file and does not read or write, so even if the path is wrong, it will not report an error)

Creates a new path with the given parent abstract pathname and child pathname strings File example.
File(File parent, String child);
Creates a new path by converting the given path name string to an abstract path name File example.
File(String pathname)
according to parent Pathname string and child Create a new path using the pathname string File example.
File(String parent, String child)
By placing a given file: URI Convert to an abstract pathname to create a new one File example.
File(URI uri)

Personally, I think the second creation method is the most common, which directly gives a path to create a file object.

Some methods of File class

####Explanation of IO flow

IO principle

  • I/O is the abbreviation of input and output. I/O technology is a very practical technology for processing data transmission between devices.
  • In Java programs, data input / output operations are performed in a "stream" manner.
  • java. Various "stream" classes and interfaces are provided under the IO package to obtain data that does not pass through the category, and input or output data through standard methods

Classification of flow

  • According to different operation data units, it is divided into byte stream (8bit) and character stream (16bit);
  • According to the flow direction of data flow, it is divided into: input flow and output flow;
  • According to the different roles of the flow, it can be divided into node flow and processing flow
Abstract base classByte stream (processing pictures)Character stream (text processing)
Input streamInputStreamReader
Output streamOutputStreamWriter

General content of File class

Test the use of FileInputStream and FileOutPutStream

Conclusion:
1. For text files (. txt,.java,.c,.cpp), use character stream processing;
2. For non text files (. kpg,. mp4,. avi,. ppt), use byte stream processing;

One of the processing streams: the use of buffer streams

1. Buffer flow

  • BufferedInputStream
  • BufferedOutPutStream
  • BufferedReader
  • BufferedWriter

2. Function: provide the read and write speed of the stream. Reasons for improving reading and writing speed; A buffer is provided internally
3. Processing flow is "socket connection": Based on the existing flow.

Processing flow 2: use of conversion flow

1. Conversion stream: digital service character stream
InputStreamReader: converts a byte input stream into a character input stream;
OutputStreamWriter: converts the output stream of one character into the output stream of bytes;
2. Function: provide conversion between byte stream and character stream
3. Decoding: byte, byte array - > character array, string
Encoding: character array, string - > byte, byte array
4. Character set

Use of object streams

1.ObjectInputStream and ObjectOupPutStream
2. Function: used to store and read basic data type data or object processing stream. Its strength is that it can write objects in Java to the data source and restore objects from the data source

Serialization process: save java objects in memory to disk or transfer them over the network
Implementation using ObjectOutputStream

3. If you want a java object to be serializable, you need to meet the corresponding requirements. The interface serializable needs to be implemented. In addition to implementing the interface, you also need to ensure that all its internal attributes must also be serializable. (by default, basic data types are serializable)

Lamdba expression

1. For example: (O1, O2) - > interger Compare(o1,o2);
2. Format:
->: lamdba operator or arrow operator;
->Left: lamdba formal parameter list (in fact, it is the formal parameter list of abstract methods in the interface)
->Right: lamdba body (actually the method body of the overridden abstract method)

Article link

Keywords: Java

Added by pieychpi on Sun, 26 Dec 2021 13:14:54 +0200