Written test oriented programming knowledge

Posted by airric on Sun, 02 Jan 2022 22:58:15 +0100

1, Scanner

Scanner is a scanner. The scanned data is scanned and read into a buffer in memory, and the data we input in the console is stored in the buffer first for scanning and reading by the scanner. The basis for the scanner to judge the stop in the scanning process is the "terminator". Spaces, carriage returns and tab s are regarded as terminators

The pit point lies in the next series, that is, the following functions:

  • next
  • nextInt
  • nextDouble
  • nextFloat

These functions have holes when used with nextLine:
The pit point is that the carriage return character (\ r) will be left in the buffer after the next series of functions return data. Therefore, we will encounter the case of reading an empty string the next time we use nextLine

Solution:

  • nextLine is used for format conversion
  • After entering the next series of function calls, call nextLine once in the middle. After removing the carriage return, call nextLine again to really input our data

Read a limited number of strings

All use nextLine:

import java.util.Scanner;
import java.lang.System;
import java.lang.String;
import java.lang.Integer;

class ScannerDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = Integer.parseInt(sc.nextLine());
        String[] str = new String[num];

        for (int i = 0; i < num; i++) {
            str[i] = sc.nextLine();
        }
        sc.close();
    }
}

Use next, nextLine to read the temporary carriage return and nextLine to read the real data:

import java.util.Scanner;
import java.lang.System;
import java.lang.String;

class ScannerDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        String[] str = new String[num];
        
        sc.nextLine();
        for (int i = 0; i < num; i++) {
            str[i] = sc.nextLine();
        }
        sc.close();
    }
}

Both methods can solve the problem that the string with spaces can be read, and the abnormal empty string will not be read.

Error prone point

  • nextLine() will read null value after nextInt() or next() is read and carriage return followed by nextLine(), because nextLine() automatically reads' \ n ', which means that an terminator is encountered;
  • Sometimes, when converting a string to an integer, the code prompts that the array is out of bounds when there is no problem. It is often because the integer represented by the string exceeds the maximum value of int, so you need to use long instead.

Scanner performance
Scanner is really too slow. It has always been written in BufferReader, but today it timed out when trying, so it was too late to use BufferReader again
In the final analysis, because Scanner implements diversified operations on input characters, BufferReader is relatively single, and what it reads is a byte stream converted into a string
In the actual test, BufferReader is at least twice as fast as Scanner input
Scanner is used for the function of circular input, that is, the function of hasNext() method

Today, I suddenly thought that I can use an dead loop instead, so I'd better continue to use BufferReader! Boy! Scanner performance

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.System;
import java.lang.String;
import java.lang.Integer;

class Main{
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int num = Integer.parseInt(bf.readLine());
        String[] str = new String[num];
        int i = 0;
        while (true) {
            if (i >= num) {
                bf.close();
                break;
            } else {
                str[i++] = bf.readLine();
                System.out.println(str[i-1]); // Cyclic input
            }
        }
    }
}

Read consecutive integers

Input: includes two positive integers a and B (1 < = a, B < = 10 ^ 9). The input data includes multiple groups.
Output: the result of a+b.

import java.util.Scanner;
import java.lang.System;

public class Main{
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        while(in.hasNext()){
            int a=in.nextInt();
            int b=in.nextInt();
            System.out.println(a+b);
        }
    } }

Read finite integers

Input: the first row includes a number of data groups t (1 < = T < = 100), and the next row includes two positive integers a and B (1 < = a, B < = 10 ^ 9)
Output: result of a+b

import java.util.Scanner;
import java.lang.System;

public class Main{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        while(n-->0){
            int a=in.nextInt();
            int b=in.nextInt();
            System.out.println(a+b);
        }
    }
}

Read space separated integers per line

Input: there are multiple groups of input data, and each line represents a group of input data. Each line may have n integers separated by spaces. (1 <= n <= 100).
Output: output the sum result of each group of data

import java.util.Scanner;
import java.lang.System;
import java.lang.String;
import java.lang.Integer;

public class Main{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        while(in.hasNext()){
            String[] temp=in.nextLine().split(" ");
            int sum=0;
            for(String s:temp)
                sum+=Integer.valueOf(s);
            System.out.println(sum);
        }
    }
}

2, Collection

Single column set frame structure
Collection interface: single column collection, used to store objects one by one

  • List interface: store ordered and repeatable data. -- > Dynamic array
    • ArrayList,LinkedList,Vector
  • Set interface: stores unordered and non repeatable data -- > high school's "set"
    • HashSet,LinkedHashSet,TreeSet

Common methods of Collection interface:
add(Object obj), addAll(Collection coll), size(), isEmpty(), clear(),
contains(Object obj), containsAll(Collection coll), remove(Object obj),
removeAll(Collection coll), retainsAll(Collection coll), equals(Object obj);
hasCode(), toArray(), iterator();

Conversion between Collection and array

Two ways to traverse a Collection

  • ① Use Iterator (Iterator interface defined under Java. Utils package: Iterator)
  • ② foreach loop (or enhanced for loop)
import java.util.*;

public class CollectionMapTest {
    public static void main(String[] args) {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add("asd");
        coll.add(false);
        // Iterator iterator
        Iterator iterator = coll.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
            
        }
        // for each enhanced loop
        for (Object obj : coll) {
            System.out.println(obj);
        }
    }
}

List

common method

  • Add: add(Object obj)
  • Delete: remove(int index) / remove(Object obj)
  • Change: set(int index, Object ele)
  • Query: get(int index)
  • Insert: add(int index, Object ele)
  • Length: size()
  • Traversal:
    • ① Iterator iterator mode
    • ② Enhanced for loop
    • ③ Ordinary cycle

List interface: store ordered and repeatable data. -- > Dynamic array

  • Common implementation classes: ArrayList, LinkedList, Vector
import java.util.*;

public class CollectionMapTest {
    public static void main(String[] args) {
        List<Integer> l1 = new ArrayList<>();
        ArrayList<String> l2 = new ArrayList<>();
        
        List<Character> l3 = new LinkedList<>();
        LinkedList<Object> l4 = new LinkedList<>();
        
        List<Object> l5 = new Vector<>();
        List<Object> l6 = new Stack<>();
        Vector<Object> l7 = new Stack<>();
    }
}

Common implementation classes for List collections
1. ArrayList set: implementation of variable size array of List interface. (fast query, slow addition and deletion.) this implementation is not synchronous (multithreading problem).
2. LinkedList set: the linked List implementation of the List interface. This implementation is not synchronized.
java.util.LinkedList set implements List interface
characteristic:
① The bottom layer is a linked list structure: slow query and fast addition and deletion.
② , which contains a large number of methods to operate the beginning and end elements.
Note: use the methods specific to the LinkedList collection, and polymorphism cannot be used.
- public void addfirst (E): inserts the specified element at the beginning of this list.
- public void addlast (E): adds the specified element to the end of this list.
- public E getFirst(): returns the first element of this list.
- public E getLast(): returns the last element of this list.
- public E removeFirst(): removes and returns the first element of this list.
- public E removeLast(): removes and returns the last element of this list.
- public E pop(): pop an element from the stack represented by this list. Equivalent to removeFirst().
- public void push (E): push elements into the stack represented by this list. Equivalent to addfirst (E).
- public boolean isEmpty(): returns true if the list does not contain elements.
—clear(); // Clearing the elements in the collection and getting the elements in the collection will throw NoSuchElementException.
3. Vector set: an array of objects that can grow. This implementation is synchronous. JDK1.0 is the earliest collection. The bottom layer is also an array, but it is single threaded and slow.

Java Dual Ended queue Deque implementation stack

[Java] Java double ended queue Deque usage details

Implementation of queue

import java.util.LinkedList;
import java.util.Queue;

Queue<Node> queue1 = new LinkedList<>();
// add(), offer(); remove(), poll(); element(), peek()
LinkedList<Node> queue1 = new LinkedList<>();
// addLast(), offerLast(); removeFirst(), pollFirst(); element(), peekFirst()

Difference between offer and add: (
Some queues have size limits, so if you want to add a new item to a full queue, the extra items will be rejected. Then the new offer method can work. Instead of throwing an unchecked exception for calling the add() method, it just gets false returned by offer().

poll, remove differences:
Both the remove() and poll() methods remove the first element from the queue. The behavior of remove() is similar to the version of the Collection interface, but the new poll() method does not throw an exception when called with an empty Collection, but returns null. Therefore, the new method is more suitable for situations prone to abnormal conditions.

peek, element difference:
element() and peek() are used to query for elements at the head of the queue. Similar to the remove() method, when the queue is empty, element() throws an exception and peek() returns null.

Implementation of stack

import java.util.LinkedList;
import java.util.Deque;

Deque deque = new LinkedList()

Set

common method

No new methods are defined in the Set interface, but all the methods declared in the Collection are used.

Set interface: unordered and unrepeatable elements -- > high school's "set"

  • Common implementation classes: HashSet, LinkedHashSet, TreeSet
import java.util.Set;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeHashSet;

Set<String> set1 = new HashSet<String>();  
Set<String> set2 = new LinkedHashSet<String>(); 
Set<String> set3 = new TreeSet<String>();  

3, Map

Two column set framework: Map

Common implementation class structure: Map: double column data, storing data of key value pairs - similar to high school function: y = f(x)

  • HashMap: as the main implementation class of Map; Unsafe thread and high efficiency; Store null key and value
    • LinkedHashMap: ensure that when traversing map elements, traversal can be implemented 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 efficiency is higher than HashMap.
  • TreeMap: ensure that the added key value pairs are sorted 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

Key in Map: unordered and non repeatable. Use Set to store the key - > the class where the key is located should override equals() and hashCode() (take HashMap as an example)
Value in the Map: unordered and repeatable. Use the value stored in the Collection - the class where value is located should override equals()
A key value pair: key value constitutes an Entry object.
Entry in Map: unordered and non repeatable. Set is used to store the entry

common method

  • Add: put(Object key,Object value)
  • Delete: remove(Object key)
  • Modify: put(Object key,Object value)
  • Query: get(Object key)
  • Length: size()
  • Traversal: keySet() / values() / entrySet()

4, Collections tool class

Function: tool class for operating Collection and Map

common method

  • reverse(List): reverses the order of elements in the List
  • shuffle(List): randomly sort the elements of the List collection
  • sort(List): sorts the elements of the specified List set in ascending order according to the natural order of the elements
  • sort(List, Comparator): sort the List collection elements according to the order generated by the specified Comparator
  • swap(List, int, int): exchange the elements at i and j in the specified list set
  • Object max(Collection): returns the largest element in a given collection according to the natural order of elements
  • Object max(Collection, Comparator): returns the largest element in a given collection according to the order specified by the Comparator
  • Object min(Collection)
  • Object min(Collection,Comparator)
  • int frequency(Collection, Object): returns the number of occurrences of the specified element in the specified collection
  • void copy(List dest,List src): copy the contents of src to dest
  • Boolean replaceall (List, Object oldVal, Object newVal): replaces the old value of the List object with the new value
  • Note: both ArrayList and HashMap are thread unsafe. If the program requires thread safety, we can convert ArrayList and HashMap into thread. Use synchronized list (list) and synchronized map (map)

expand

Collection details