Java Interview Questions

1. Introduce the structure of the Collection framework

Collection is a very important knowledge point in Java, which is mainly divided into three data structures: List, Set, Map, and Queue. Their structural relationship in Java is as follows:

The Collection interface is the parent interface of List, Set, and Queue.

The Set interface has two commonly used implementation classes: HashSet and TreeSet. Commonly used interfaces of List interface are ArrayList and Vector interface.

The Map interface has two commonly used implementation classes: Hashtable and HashMap.

2. What interface should be implemented to implement comparison in the Collection framework

There are two ways to implement the comparison: First, the entity class implements the Comparable<T> interface and implements the compareTo(T t) method, which we call the internal comparator. Second, create an external comparator that implements compare(T t1, T t2) of the Comparator interface.

The first is to implement the Comparable interface:

copy code
package com.chanshuyi.comparable;

import java.util. * ;

public class Student implements Comparable<Student> {

    private String name;

    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        if ( getAge() > o.getAge()) {
            return 1;
        } else if ( getAge() < o.getAge()) {
            return -1;
        } else {
            return 0;
        }
    }

    // Override toString() to output 
    public String toString() {
         return "[" + name + "," + age + "]" ;
    }

    public static void main(String args[]){
        Student s1 = new Student("Tom", 12);
        Student s2 = new Student("Marry", 9);
        Student s3 = new Student("Json", 88);

        List<Student> studentList = new ArrayList<Student>();
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);

        Collections.sort(studentList);
        System.out.printf("Original  sort, list:%s\n", studentList);
    }
}
copy code

Second, implement the Comparator interface:

First define a Student class without implementing any interface.

  View Code

Define an external comparator class that implements the Comparator interface:

  View Code

It can be seen that if you want the entity class to be sorted in the way you want when it is put into the collection (if the collection supports it), then you need to make the entity class implement the Comparable interface. If you just need to simply compare the size of two entity classes and finally return a result, then implementing an external comparator using the Comparator interface is more appropriate.

3. The difference between ArrayList and Vector (whether ordered, repeated, data structure, underlying implementation)

Both ArrayList and Vector implement the List interface, they are all ordered collections, and the stored elements are allowed to be repeated. The bottom layer of them is implemented by arrays, so the data structure of the list is fast to retrieve data, but the speed of addition, deletion and modification is slow.

The difference between ArrayList and Vector is mainly in two aspects:

First, thread safety. Vector is thread safe while ArrayList is thread unsafe. Therefore, if the collection data is only accessed by a single thread, then using ArrayList can improve efficiency. And if you have multiple threads accessing your collection data, then you must use Vector, because you want to ensure data security.

Second, data growth. Both ArrayList and Vector have an initial capacity size. When the elements stored in them exceed the capacity, their storage capacity needs to be increased. ArrayList grows by 0.5 times the original size each time, while Vector grows double the original size. Both ArrayList and Vector can set the size of the initial space, and Vector can also set the size of the growth space, while ArrayList does not provide a method to set the growth space.

4. The difference between HashMap and Hashtable

Both HashMap and Hashtable implement the Map interface and are both key-value data structures. They differ mainly in three aspects:

First, Hashtable is a Java 1.1 class based on the obsolete Dictionary class. The HashMap is an implementation of the Map interface introduced by Java 1.2.

Second, Hashtable is thread-safe, which means that it is thread-synchronized, while HashMap is thread-unsafe. That is to say, HashMap should be used in a single-threaded environment, which is more efficient.

Third, HashMap allows null values ​​as key or value, but Hashtable does not (a NullPointerException will be thrown).

5. What is the difference between List and Map? (data structure, storage characteristics)

This should be answered from two aspects, one is the data structure of List and Map, and the other is the characteristics of stored data. In terms of data structure, List stores a collection of single-column data, while Map stores data collections of key and value types. In terms of data storage, the data stored in List is ordered and repeatable, while the data stored in Map is unordered and the key value cannot be repeated (the value value can be repeated).

6. What are the characteristics of the three interfaces of List, Map and Set when accessing elements?

List and Set are similar in that they are collections of single-column elements, so they have a common parent interface called Collection. Duplicate elements are not allowed in the Set. The so-called repetition means that there cannot be two equal (note, not just the same) objects, that is, suppose there is an A object in the Set collection, and now I want to store another one in the Set collection. B object, but the B object is equal to the A object, so the B object is not stored. Therefore, the add method of the Set collection has a return value of boolean. When there is no element in the collection, when the add method can successfully add the element, it returns true. When the collection contains an element equal to an element equals, At this time, the add method cannot add the element, and the return result is false. When Set takes elements, there is no way to say which one is taken. You can only use the Iterator interface to get all the elements, and then traverse each element one by one.

List represents a collection in order. Note that it is not sorted by age, size, or price. When we call the add(Obj e) method multiple times, the objects added each time are in a first-come-last-arrival order, just like the train station has a queuing order for buying tickets. Sometimes, you can also jump the queue, that is, call the add(int index, Obj e) method, you can specify the storage location of the current object in the collection. An object can be stored in the List repeatedly. Each time the add method is called, the object is inserted into the collection. In fact, the object itself is not stored in the collection, but an index variable is used in the collection to point to it. This object, when the object is added multiple times, is equivalent to multiple indexes in the collection pointing to this object, as shown in Figure x. In addition to getting all the elements in the Iterator interface and traversing each element one by one, the List can also call get(index i) to specify the number to be retrieved.

Map is different from List and Set. It is a collection of two columns. There is a put method, which is defined as follows: put(obj key, obj value). Each time it is stored, a pair of key/value must be stored, and duplicate keys cannot be stored. This repetition rule also compares equals by equals. You can get the corresponding value according to the key, that is, the return value of get(Object key) is the value corresponding to the key. In addition, you can also get the combination of all keys (map.keySet()), the combination of all values ​​(map.values()), and the set of Map.Entry objects composed of keys and values ​​( map.entrySet()).

List holds elements in a specific order, and can have repeating elements. Set cannot have duplicate elements, internal sorting. Map saves the key-value value, the value can be multiple

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325728354&siteId=291194637