JavaSE module 3 Notes

Phase I - module III

1, lang package

1. Object class

1.1 common methods

1.1.1 equals method

By default, the addresses of two objects are compared. You can customize the comparison rules by overriding the equals method.

When the calling object is not empty and the parameter object is empty, the comparison result is empty.

// Implementation of equals method in Object class
public boolean equals(Object obj) {
    return (this == obj);
}

// Override the equals method
public boolean equals(Object obj) {
    // When the calling object and the parameter object point to the same object, the content must be the same.
    if (this == obj) {
        return true;
    }
    // When the calling object is not empty and the parameter object is empty, the comparison result is empty.
    if (obj == null) {
        return false;
    }
    if (obj instanceof Student) {
        Student s = (Student) obj;
        return this.getId() == s.getId();
        // If it is a comparison reference type, you need to use String; Class to compare whether the strings are the same.
        // return this.getName().equals(s.getName());
    }
    return false;
}
1.1.2 hashcode method

When rewriting the equals method, you usually need to rewrite the hashcode method at the same time, because when two objects are equal according to the equals method, the hashcode value must also be the same.

1.1.3 toString method
  • The user gets the string form of the object. The default string returned by this method is: package name Class name @ Hex of hash code. For example: pers kyle. java. mylang. Student@15db9742

  • The toString method will be called automatically when using print or println to print references or string splicing references

    // s1 is the Student object
    System.out.println(s1);
    System.out.println("hello" + s1);
    

Therefore, it is usually necessary to override the toString method

2. Packaging

Class 1.2 integer packaging

2.1.1 written examination points for packing and unpacking
Integer i1 = 127;
Integer i5 = 128;
Integer i2 = 127;
Integer i6 = 128;

Integer i3 = new Integer(127);
Integer i7 = new Integer(128);
Integer i4 = new Integer(127);
Integer i8 = new Integer(128);

System.out.println(i1 == i2);		// true
System.out.println(i5 == i6);		// false
System.out.println(i7.equals(i8));	// true
System.out.println(i3 == i4);		// false

Note: the automatic packing pool technology is provided inside the Integer class. The integers between - 128 and 127 have been boxed. When the integers in this range are used in the program, the objects in the automatic packing pool can be used directly without boxing, so as to improve the efficiency.

2.2 application summary of packaging

  • How to convert the basic data type to the corresponding wrapper class: call the constructor or static method of the wrapper class (recommended).

    Integer v = Integer.valueOf(123);
    Integer v = Integer.valueOf("123");
    
  • How to get the value of the basic data type variable in the wrapper class object: call the xxxValue method in the wrapper class.

    Double d = 3.14;
    double dv = d.doubleValue();
    
  • How to convert a string to a basic data type: call the parseXxx method of the wrapper class.

    int i = Integer.parseInt("123");
    

3. Digital processing

3.1 BigDecimal class

3.1.1 basic concepts

Because float and double types may have errors in operation, if you want to realize accurate operation, you can use Java Lang. BigDecimal type.

3.1.2 common methods
Method declaration Function introduction
BigDecimal(String s) Constructs an object based on the string specified by the parameter
BigDecimal add(BigDecimal b) It is used to realize addition operation
BigDecimal subtract(BigDecimal b) Used to implement subtraction
BigDecimal multiply(BigDecimal b) Used to realize multiplication
BigDecimal divide(BigDecimal b) Used to implement division
3.1.3 precautions
BigDecimal b1 = new BigDecimal("2");
BigDecimal b2 = new BigDecimal("0.3");
System.out.println(b1.devide(b2));  // An error will be reported because the result cannot get an exact value and is an infinite circular decimal.
// If you want to get the result, you need to specify the discard rule
System.out.println(b1.devide(b2, RoundingMode.HALF_UP));

4. String class (key)

4.1 concept of constant pool

Since the String content described by the String type is constant and cannot be changed, the Java virtual machine puts the String that appears for the first time into the constant pool. If the same String content appears in subsequent codes, the existing String objects in the pool will be used directly without applying for memory and creating objects, so as to improve performance.

// So far, only String, a special class, can directly assign values to strings in addition to handling new
String s1 = "123";
String s2 = "123";
System.out.println(s1 == s2);  // true

4.2 interview site

String s1 = "hello";	// This code will only create one object and store it in the constant pool
String s2 = new String("hello"); // Two objects will be created, one in the constant pool and one in the heap.
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello"); 

System.out.println(s1 == s2);  // true
System.out.println(s1.equals(s2));  // String overrides the equals method and the result is true
System.out.println(s3 == s4); // false 
System.out.println(s3.equals(s4)); // true
System.out.println(s2 == s4); // false
System.out.println(s2.equals(s4)); //true
// Constant has optimization mechanism, variable has no optimization mechanism
String s1 = "hello";
String s2 = "hel" + "lo";
System.out.println(s1 == s2); // true, constant optimization mechanism

String s3 = "hel";
String s4 = s3 + "lo";
System.out.println(s1 == s4); // false

4.3 conversion between string and array

String s1 = "hello";
byte[] b = s1.getBytes();		// Convert to byte array
char[] c = s1.toCharArray();	// Convert to character array

4.4 convert String to int type

Written examination site

// Method 1: call parseInt method in Integer class
String s1 = new String("12345");
int i = Integer.parseInt(s1);

// Method 2: use ASCII code to realize
int res = 0;
for (i = 0; i < s1.length(); i++) {
    res = res * 10 + s1.charAt(i) - '0';
}
System.out.println(res);

4.4 case title

Judge whether the string "Shanghai tap water comes from the sea" is a palindrome

String s1 = new String("Shanghai's tap water comes from the sea");
// Cycle to (args.length) / 2
for (int i = 0; i < (args.length) / 2; i++) {
    if (s1.charAt(1) != s1.charAt(s1.length() - i - 1)) {
        System.out.println(s1 + " Not palindromes");
        return;
    }
}
System.out.println(s1 + " It's palindrome");

5. Variable string class

5.1 StringBuffer

It belongs to thread safe class, so its efficiency is relatively low.

5.2 StringBuilder (key)

It is a non thread safe class with high efficiency.

5.2.1 common construction methods
Method declaration Function introduction
StringBuilder() The object is constructed without parameters, with a capacity of 16
StringBuilder(int capcity) The size of the constructed object is specified according to the capacity parameter
StringBuilder(String str) The object is constructed according to the capacity specified by the parameter. The capacity is 16 + string length

Sample code

// Nonparametric structure
StringBuilder sb1 = new StringBuilder();
System.out.println("sb1 = " + sb1);
System.out.println("The capacity is:" + sb1.capacity());
System.out.println("The length is:" + sb1.length());

// Parameter structure, specify the capacity size
StringBuilder sb2 = new StringBuilder(5);
System.out.println("------------------------");
System.out.println("sb2 = " + sb2);
System.out.println("The capacity is:" + sb2.capacity());
System.out.println("The length is:" + sb2.length());

// Parameterized construction, specifying the initial string
StringBuilder sb3 = new StringBuilder("abc");
System.out.println("------------------------");
System.out.println("sb3 = " + sb3);
System.out.println("The capacity is:" + sb3.capacity());
System.out.println("The length is:" + sb3.length());
5.2.2 common member methods
Method declaration Function introduction
int capacity() Used to return the capacity of the calling object
int length() Used to return the length of a string, that is, the number of characters
StringBulider insert(int offset, String str) Insert the string and return the reference of the calling object, which is itself.
StringBulider append(String str) Append string
StringBulider deleteCharAt(int index) Deletes a single character with index in the current string
StringBulider delete(int start, int end) Delete string
StringBulider delete(int start, int end, String str) Replace string
StringBulider reverse() String inversion
5.2.3 automatic capacity expansion

When the string length exceeds the initial capacity of the string object, the string object will be automatically expanded. The default expansion algorithm is: original capacity * 2 + 2.

5.2.4 design of return value

The return value of many methods of StringBulider is of type StringBulider. The return statements of these methods are: return this

It can be seen that these methods return the reference of the object after changing the string sequence encapsulated by StringBuilder. The purpose of this design is that they can be called continuously.

6. Date, SimpleDateFormat and Calendar classes

The three classes are used together, and the example code is as follows:

// Date d1 = new Date(2008-1900, 8-1, 8, 20, 8, 8 );  //  obsolete
Calendar calendar = Calendar.getInstance();
calendar.set(2008, 8, 8-1, 20, 8, 8);
Date d2 = calendar.getTime();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// String format = sdf.format(d1);
String format = sdf.format(d2);

System.out.println("The obtained time is:" + format);

7. Date time class in Java 8

The example code is as follows:

LocalDateTime dateTime = LocalDateTime.now();
System.out.println("The current date and time obtained is: " + dateTime);

// User defined month, day, hour, minute and second
LocalDateTime of = dateTime.of(2008, 8, 8, 20, 8, 8);
System.out.println("The specified date and time is: " + of);
System.out.println("The year obtained is:" + of.getYear());
System.out.println("The obtained month is:" + of.getMonthValue());
System.out.println("The date obtained is:" + of.getDayOfMonth());
System.out.println("The hours obtained are:" + of.getHour());
System.out.println("The minutes obtained are:" + of.getMinute());
System.out.println("The seconds obtained are:" + of.getSecond());

Note: the method of setting features (withXxx, plusXxx, minusXxx) returns the type of LocalDateTime, but it is a new LocalDateTime object, and the original LocalDateTime object has not changed, just like String.

8. Collection class library (key)

8.1 Collection

8.1.1 basic concepts
  • java.util.Collection interface is the parent interface of List interface, Queue interface and Set interface
8.1.2 common methods
Method declaration Function introduction
boolean add(E e) Add elements to the collection
boolean addAll(Collection<? extends E> c) Adds all elements in the collection specified by the parameter to the current collection
boolean contains(Object o) Determine whether the specified object is included
boolean retainAll(Collection<? > c) Retains elements that exist in the current collection and in the collection specified by the parameter
boolean remove(Object o) Deletes the element specified by the parameter
boolean removeAll(Collection<? > c) Deletes all elements in the collection specified by the parameter
void clear() Empty collection
int size() Number of collection elements
Object[] toArray() Convert a collection to an array
Iterator iterator() Gets the current collection iterator

Methods needing attention

  • contains method
Collection c = new ArrayList();
System.out.println("The elements in the collection are:" + c);

boolean b1 = c.add("one");//Automatic packing
boolean b1 = c.add(new String("one"));
boolean b2 = c.add(2);
boolean b3 = c.add(new Person("Zhang San", 18));
System.out.println("The elements in the collection are:" + c);//The elements in the set are: [one, 2, Person [name = Zhang San, age=18]]

boolean b4 = c.contains(new Person("Zhang San", 18));
System.out.println(b4);// false
boolean b5 = c.contains(2);
System.out.println(b5);// true
boolean b6 = c.contains(new String("one"));
System.out.println(b6);// true
// To sum up, the last thing is the address of the comparison. The java encapsulated class rewrites the equals method, so the comparison result is true. If the self-defined class does not rewrite the equals method, the comparison result is false.
  • remove method

When deleting an element, the equals method is also used to judge whether there is the element. If there is, it will be deleted and return true; Otherwise, false is returned.

Case: simulate the printing effect of toString with iterator

public class CollectionPrintTest {

	public static void main(String[] args) {
		
		// Use iterators to simulate the printing effect of toString method
		Collection c = new ArrayList();
		System.out.println("The elements in the collection are:" + c);
		
		boolean b1 = c.add("one");
		boolean b2 = c.add(2);
		boolean b3 = c.add(new Person("Zhang San", 18));
		System.out.println("The elements in the collection are:" + c);
		
		Iterator iterator = c.iterator();
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		while (iterator.hasNext()) {	
			Object next = iterator.next();
			if (!iterator.hasNext()) {
				sb.append(next).append("]");
			}else {
				sb.append(next).append(",").append(" ");
			}
		}
		System.out.println(sb.toString());
	}
}

8.2 List set (top priority)

  • The set allows duplicate elements and has the order in which they are placed.

  • The main implementation classes of this collection include ArrayList class, LinkedList class, Stack class and Vector class

  • How to traverse the List set: Iterator, for each, toString

8.2.1 ArrayList class
List list = new ArrayList();
list.add(2);
System.out.println(list);
  • ArrayList source code analysis
// First line of code
List list = new ArrayList();
// Enter the source code
public ArrayList() {
    // elementData = Object[]
    // DEFAULTCAPACITY_EMPTY_ELEMENTDATA = Object[] = {}
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

// According to the source code, new ArrayList(); This code is equivalent to just creating an Object [] with a length of 0 and not applying for memory space for the array

// Second line of code
list.add(2);
// Enter the source code
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

// Then enter ensureCapacityInternal(size + 1); This line of code
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// Then enter the calculateCapacity method
private static int calculateCapacity(Object[] elementData, int minCapacity) {
    // Condition is true
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        // DEFAULT_ The default value of capability is 10 and minCapacity is 1, so the last returned value is 10 
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
    
// After jumping out, enter the ensureExplicitCapacity method
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        // The minCapacity passed in here is 10, so the condition holds
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
// Enter the grow th method
    private void grow(int minCapacity) {
        // overflow-conscious code
        // oldCapacity = 0
        int oldCapacity = elementData.length;
        // newCapacity = 0
	   // Core code, 1.5 times capacity expansion each time
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            // Enter here, newCapacity = 10
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        // Here, the core re applies for an array with a length of newCapacity, that is, an array with a length of 10.
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    
 // Here, the core source code is finished, and then start to execute the following line of code
 elementData[size++] = e; // Assign 2 to the first element of the new array

There are two core points in the above source code

First: array expansion algorithm: newcapacity = oldcapacity + (oldcapacity > > 1)

Second: update array: elementdata = arrays copyOf(elementData, newCapacity)

8.2.2 LinkedList class

Source code analysis

List list = new LinkedList();
list.add(2);
System.out.println(list);

// Source code analysis
List list = new LinkedList();// This line of code actually creates an empty list
// The next line of code
list.add(2);
// Enter the source code
public boolean add(E e) {
    linkLast(e);
    return true;
}
// Enter the linkLast method
// Links e as last element.
void linkLast(E e) {
    final Node<E> l = last;	// last == null
    // Call the construction method to generate a new node. This node is the last node, so its next node is null,
    // The last node is last
    final Node<E> newNode = new Node<>(l, e, null);	
    last = newNode; // The front and back nodes are empty
    if (l == null)	// If the previous node is also null
        first = newNode;	// Then this node is both the first node and the last node.
    else
        l.next = newNode;
    size++;
    modCount++;
}

// Node is a static internal class that represents a node. The source code is as follows
private static class Node<E> {
    E item;			// The value of the current node
    Node<E> next;	// The next node of the current node
    Node<E> prev;	// The next node of the current node

    // Construction method
    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}
8.2.3 common methods
Method declaration Function introduction
void add(int index, E element) Adds an element to the specified location in the collection
boolean addAll(int index, Collection<? extends E> c) Add all elements to the collection
E get(int index) Gets the element at the specified location from the collection
int indexOf(Object o) Find the object specified by the parameter
int lastIndexOf(Object o) Reversely finds the object specified by the parameter
E set(int index, E element) Modify the element at the specified location
E remove(int index) Deletes the element at the specified location
List subList(int fromIndex, int toIndex) Used to get child List

It should be noted that the List returned by the subList method and the original List share the same memory space

List l2 = new LinkedList();
l2.add(2);
l2.add("one");
l2.add("two");
System.out.println(l2);
List subl2 = l2.subList(0,2);
System.out.println(subl2);
System.out.println("-------------");
subl2.remove(1);
System.out.println(subl2);
System.out.println(l2);

// The execution result of the code is as follows
//[2, one, two]
//[2, one]
//-------------
//[2]
//[2, two]

// It reflects the common of memory space
8.4 Stack type

8.3 Queue set (key)

  • The main implementation class of this collection is LinkedList
8.3.1 common methods
Method declaration Function introduction
boolean offer(E e) Add an object to the end of the queue, and return true if the addition is successful
E poll() Deletes and returns an element from the head of the queue
E peek() Returns the element at the head of the queue (but does not delete it)

8.4 generics (familiar)

  • Generics are only valid at compile time, and there are no generics at run time.
  • Generics can only be used to reference data types, and cannot be basic data types
8.4.1 custom generic classes
public class Person<T> {
    private String name;
    private int age;
    private T gender;
    ...
}

public class PersonTest {

    public static void main(String[] args) {

        // If no generic type is specified, it is handled by Object type by default
        Person p1 = new Person("zhangsan", 20, "male");
        System.out.println(p1);
        p1.setGender("nan");

        // Specify generics
        Person<String> p2 = new Person<>();
        System.out.println(p2);

    }
}

Ways to inherit generic classes

//Public class student extensions Person {does not retain generics and does not specify a type. At this time, T in the Person class defaults to Object type
//Public class student extensions Person < String > {does not retain generics, but specifies the type of generics. At this time, T in Person class is specified as String type
//Public class student < T > extends person < T > {/ / keep the generics of the parent class
    public class Student<T,T1> extends Person<T>{// Keep the generics of the parent class, and add additional generics to the child class
}
8.4.2 custom generic methods (key points)

Syntax format of generic methods

[access rights] < generic > return value type method name ([Generic identification parameter name]) {method body;}

public <T2> void printArray(T2[] arr){
    Method body
}

// The parameter is generic and the return value is generic
public <T2> T2[] toArray(T2[] arr) {
    Method body
}
8.4.3 generic wildcards (familiar)
  • Unrestricted wildcard: indicates that we can pass in any type of parameter.
  • The upper bound of the representation type is e, which can only be e or a subclass of E.
  • The lower bound of the representation type is e, which can only be e or the parent of E.
// Unrestricted wildcard, that is, it can be any data type and cannot add elements
List<?> l1 = new LinkedList<>();
//l1.add(new Animal()); Error, if the generic type is a Dog type, you can't put the animal type
//l1.add(new Dog());Error
//l1.add(new Object());Error
System.out.println("----------------------");

// Cannot add element
List<? extends Animal> l2 = new LinkedList<>();
//l2.add(new Animal()); Error, if the generic type is a Dog type, you can't put the animal type
//l2.add(new Dog()); Error, what if a cat inherits the Animal class? If the generic type is cat, you can't put dog

System.out.println("----------------------");

// You can add elements
List<? super Animal> l3 = new LinkedList<>();
l3.add(new Animal());
l3.add(new Dog());
//l3.add(new Object()); Error

8.5 Set (familiar)

8.5.1 HashSet class

How elements are put into the HashSet set set

  • Use the element to call the hashCode method to obtain the corresponding hash code value, and then calculate the index position of the element in the array by a hash algorithm.

  • If there is no element in this position, you can put the element directly.

  • If there is an element in this position, the new element is used to compare the hash value with the existing element in turn. If the hash value is different, the element is put directly into the.

  • If the hash value of the new element is the same as that of the existing element, the new element is used to call the equals method to compare with the existing element in turn.

  • If they are equal, the addition of elements fails. Otherwise, the elements can be directly put in.

Think: why do you need to rewrite the hashCode method after rewriting the equals method?

When two elements call the equals method equally, it is proved that the two elements are the same. After rewriting the hashCode method, ensure that the hash code values obtained by the two elements are the same, and the index position generated by the same hash algorithm is the same. At this time, it only needs to be compared with the existing elements in the index position, so as to improve efficiency and avoid the occurrence of duplicate elements.

8.5.2 TreeSet class

Because the bottom layer of TreeSet set adopts red black tree for data management, when a new element is inserted into TreeSet set, it is necessary to compare the new element with the existing elements in the set in order to determine the reasonable position of the new element.

Since you need to compare sizes, you need to set comparison rules. There are two ways to compare element sizes:

  • Use the natural sorting rules of elements to compare and sort, and let the element type implement Java Lang. comparable interface;
  • Use comparator rules to compare and sort. When constructing TreeSet collection, pass in Java util. Comparator interface;
8.5.3 LinkedHashSet class

8.6 Map set (key)

8.6.1 main implementation classes
  • HashMap: the bottom layer adopts hash table
  • TreeMap: red and black trees are used at the bottom
  • LinkedHashMap: the bottom layer adopts two-way list
8.6.2 main methods
Method declaration Function introduction
V put(K key, V value) Store the Key Value pair into the Map. If the set already contains the Key, replace the Value corresponding to the Key. The return Value is the original Value corresponding to the Key. If there is no Key, return null
V get(Object key) Returns the Value object corresponding to the parameter Key. If it does not exist, it returns null
boolean containsKey(Object key); Judge whether the set contains the specified Key
boolean containsValue (Object value); Determines whether the collection contains the specified Value
V remove(Object key) Delete according to the key specified in the parameter
Set keySet() Returns the Set view of the keys contained in this map
Collection values() Returns the Set view of the values contained in this map
Set<Map.Entry<K,V>> entrySet() Returns the Set view of the mappings contained in this mapping
8.6.3 principle of putting elements into HashMap set
  • Use the key of the element to call the hashCode method to obtain the corresponding hash code value, and then calculate the index position in the array by some hash algorithm.
  • If there is no element in this position, you can put the key value pair directly.
  • If there is an element in this position, use the key to compare the hash value with the existing element in turn. If the hash value is different, put the element directly into.
  • If the hash value of the key is the same as that of the existing element, use the key to call the equals method to compare with the existing element in turn. If they are equal, modify the corresponding value; otherwise, put the key value pair directly.

9.Collections class

9.1 common methods

  • max
  • min
  • copy, the first parameter is the destination set, and the second parameter is the original set.
  • sort
  • shuffle
  • reverse

Tags: Java

Posted by rallan on Fri, 13 May 2022 12:45:55 +0300