1. Three characteristics of object orientation

Key words: encapsulation, inheritance, polymorphism

The three main characteristics of object orientation are encapsulation, inheritance and polymorphism. So how do you understand that?

We know that everything in Java is an object, and since it is an object, it must have properties and behaviors. There are properties and behaviors that we don’t want to invoke externally, such as a computer that has to be wrapped in a mainframe case because the rest of the interior is not available to the user. So Java provides encapsulation mechanisms to encapsulate objects, and we can control access to specify who can access and manipulate them.

Inheritance is equivalent to using a common part of an object. Creating a new class like this every time would be both too cumbersome and too decoupled. Java provides inheritance mechanisms that allow you to create new classes that inherit from previous classes, abstract classes, and interfaces.

Polymorphism is equivalent to using the characteristics of an object that are different from its parent class. No object is exactly the same, and there are bound to be differences. Java provides a polymorphic mechanism for parent type references to subtype objects, which makes calling code more flexible. The JVM only looks at the parent type at compile time and the child type at execution time. So the coupling is very small.

2. Load factor of HashMap

Keywords: 0.75, Poisson distribution

First look at the source code (intercept) :

public class HashMap<K.V> extends AbstractMap<K.V>
    implements Map<K.V>, Cloneable.Serializable {
    	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    	static final float DEFAULT_LOAD_FACTOR = 0.75 f;
}
Copy the code

The initial capacity of the HashMap is 16, and its default load factor is 0.75.

Why is the HashMap load factor 0.75? Java technology stack, share the most mainstream Java technology -CSDN blog

HashMap is an array + linked list data structure, but if the array is set too large, it may be too scattered, resulting in low occupancy; If the score group is set too small, it will eventually fill up and run out of space.

How to solve the problem when there is no space? There are many methods, linear detection, square detection, pseudo-random detection, rehash, chain address method. HashMap clearly uses the chain address method.

Look at the comments in the source code:

/*Ideally, under random hashCodes, the frequency of * nodes in bins follows a Poisson distribution * (http://en.wikipedia.org/wiki/Poisson_distribution) With a * parameter of about 0.5 on average for the default resizing * threshold of 0.75, although with a large variance because of * resizing granularity. Ignoring variance, The expected * occurrences of list size k are (exp(-0.5) * POw (0.5, k) / * factorial(k)). The first values are: * * 0: 0.60653066 * 1: 0.30326533 * 2: 0.07581633 * 3: 0.01263606 * 4: 0.00157952 * 5: 0.00015795 * 6: 0.00001316 * 7: 0.00000094 * 8: 0.00000006 * More: less than 1 in ten million */
Copy the code

If the loading factor is 0.75, the probability is 0.00000006 when the list length reaches 8, and the chance is impossible.

Patch: The load factor is 0.75, and each increment is a multiple of 2, because in the underlying HashMap, a resize method is called, which creates a new array and adds the elements of the old array to the new array by e.hash (newcap-1). The ampersand is a bit operation. When the capacity of the HashMap is a power of 2, the binary of Newcap-1 is in the form of all 1s. In this way, bitwise operation with the hash value of the added elements can be fully hashed, so that the added elements are evenly distributed in every position of the HashMap, reducing hash collisions.

3, collection: List, Set, Map who is ordered, who is unordered, what are their methods, what is the inheritance structure, expansion, thread safety, initial array

Keyword: The data structure is Array and Queue ordered, Linked, Set, Map unordered

Capacity expansion: Array correlation is 10, factor is 1, capacity expansion is 1; Hash 16, factor 0.75, double capacity

3.1 Characteristics and inheritance structure of various collections

Let’s look at the characteristics of the various collection types:

Sets are similar to arrays, but unordered.

List is a linked List, and it doesn’t matter where it’s located it doesn’t matter if the array isn’t equal, List is ordered.

A Queue is a Queue, first in, first out, last in, last out.

Hash computes the Hash value based on the key, which means that the entries are in no order.

We need to look at the respective data structures to get a clearer picture.

Collection (Top-level interface) :

| – Set: disorder (access order wrong, etc.)

| – HashSet: the underlying is a HashMap, disorderly

| – LinkedHashSet: a look at is the order list, but not repeatable

| – TreeSet: disorderly, but the tree will be sorted according to values

| – List: orderly, and repeatable

| – ArrayList: array, convenient query, access problems

| – LinkedList: list: easy to access, looking for trouble

| – Vector, thread-safe, bottom and ArrayList is similar

| – Queue, Queue, orderly, and repeatable

Map :(all subclasses are unordered and non-repeatable)

methods

Look directly at the Collection interface and the Map interface

public interface Collection<E> extends 可迭代<E> {
    int size(a);
    boolean isEmpty(a);
    boolean contains(Object o);
    boolean containsAll(Collection
        c);
    Iterator<E> iterator(a);
    Object[] toArray();
    boolean add(E e);
    boolean addAll(Collection<? extends E> c);
    boolean remove(Object o);
    boolean removeAll(Collection
        c);
    boolean retainAll(Collection
        c);
    void clear(a);
    boolean equals(Object o);
    int hashCode(a); . }Copy the code

Then according to the increase, deletion, change and check operation analysis:

  • Add: Add, addAll

  • Delete: remove, removeAll, clear

  • Change: that is, assign directly and change toArray toArray

  • Check whether isEmpty contains containsAll and retainAll equals and size

The Map interface:

public interface Map<K.V> {
	int size(a);
    boolean isEmpty(a);
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    V get(Object key);
    V put(K key, V value);
    V remove(Object key);
    void putAll(Map<? extends K, ? extends V> m);
    void clear(a); .Copy the code

Similar to the above, except that there are methods to get keys and values.

Initial capacity and expansion

Vector and ArrayList have an initial capacity of 10, load factor of 1, and double capacity

HashSet initial capacity 16, load factor 0.75, double capacity

HashMap initial capacity 16, load factor 0.75, double capacity

Comparable and Comparator

Keywords: Comparable in java.lang; Comparator in Java. Util; Comparable is not as flexible as Comparator

Comparable is under the java.lang package and Comparator is under the java.util package.

Comparable interface comparison methods:

public int compareTo(T o);
Copy the code

The system didn’t know when we wrote the compareTo method that an object called it, so we couldn’t compare the properties, but the Comparator was different. The Comparator’s method looks like this.

int compare(T o1, T o2);
Copy the code

We can pass two objects and generate a comparison strategy for them. Comparator is more like a policy pattern in design mode. Provide a variety of methods of calculation, and then substitute them with each other.

5, What are the classes of IO streams and what are their methods?

FileInputStream, FileOutPutStream, FileReader, FileWriter, BufferReader, BufferWriter, InputStreamReader, OutputStreamWriter, Ob JectInputStream, ObjectOutputStream

Reader, writer, flush, close;

What is the difference between String, StringBuffer, and StringBuilder?

String is an immutable type, and its underlying modifier is final, so every time you append to a String, you generate a new String, which takes up a lot of memory.

Stringbuffers and StringBuilders are better suited for manipulating strings, with append methods, Insert methods, reverse methods, and more.

StringBuffer is thread-safe, StringBuilder is non-thread-safe, it has no synchroized method in it.

Insert method is not commonly used, note that.

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    sb.append("sss");
    System.out.println(sb);
    sb.insert(1."sas");
    System.out.println(sb);
}

-------------------------------------------------
sss
ssasss    
Copy the code

7, The Object class is the parent of all classes, talk about its several common methods, and introduce

The Object class is the parent of all classes. It has several methods: Equals, HashCode, Clone, Finalize, Wait, Notify, notifyAll, toString, getClass, and native.

8. The difference between interfaces and abstract classes

Keywords: constructor, name, inheritance, modifier, variable constant

(1) Interfaces do not have constructors; abstract classes do

(2) The abstract class is an interface

(3) Implements is an interface and extends is an abstract class

(4) Interface support multiple inheritance, abstract class is single inheritance

(5) Interface methods are generally public, abstract class can be (JDK8 later interface methods can be implemented, abstract class is also optional)

(6) the interface is static, implementation class is not necessarily

9. What do you know about IO streams? What is the difference between BIO, NIO and AIO?

Key words: synchronous blocking, synchronous non-blocking, asynchronous blocking

BIO (Blocking IO) is a synchronous Blocking IO that uses sockets to create connections.

NIO (Non-blocking IO) is a synchronous non-blocking IO. The client communicates with the server through a Channel, which implements multiplexing.

Asynchronous Asynchronous IO (AIO) is Asynchronous non-blocking IO based on event and callback mechanisms.

10. Remove duplicate problems from HashMap

Because the keys of a hashMap cannot be the same, you can use a hashMap for deduplication.