Collect detailed sorting and interview questions

Posted by tlavelle on Thu, 16 Dec 2021 03:14:30 +0100

1. Common methods of collection interface and specific types of collections

add(): adds an element to the list collection
remove(Object o): removes the o element from the current collection
Remove all (collection coll1): subtraction removes all elements in coll1 from the current collection
size(): gets the collection size
Iterator(): returns an object of the interface implementation class to traverse the collection,
IsEmpty(): judge whether the collection is empty
Containers (object o): determines whether the current collection contains o (content)
Contaionsall (collision coll1): judge whether all elements in formal parameter coll1 exist in the current collection.
Retain all (collection Coll): get the intersection of the current collection and coll1 collection and return it to the current collection
equals(Collection coll1) determines whether the contents of two collections are consistent
hashCode(): returns the hash value of the current object
toArray(): set – array
Arrays.asList(new String[]{“111”,“222”}); Array – set

2. Usage of Iterator and problems needing attention

@Test
    public void test1(){
        Collection col = new ArrayList<>();
        col.add(123);
        col.add(456);
        col.add(new String("Tom"));
        Iterator iterator = col.iterator();
        while (iterator.hasNext()){
            if ((iterator.next()).equals(123)) {
                iterator.remove();
            }
        }
        iterator=col.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

Call hasNext() to return to the next pointer if there is a call and then call next() to get the next element of the pointer.
Note: every time you call a new iterator() method, you will get a new iterator. The default cursor defines a remove() method before the first one in the collection
The elements in the collection can be deleted during traversal. remove() in the iterator can only be called once during traversal. Pay attention to the pointer!

3. Usage of foreach syntax traversal

	//jdk5.0 started providing
	//Used to traverse collections and arrays
	Collection col = new ArrayList<>();
        	col.add(123);
        	col.add(456);
        	col.add(new String("Tom"));
	for(Object obj:col){
            	System.out.println(obj);
        	}

4. Common implementation classes and differences of list
Features: orderly and repeatable
ArrayList is mainly used to implement class threads, which is unsafe and efficient. At the bottom, the array Object[] elementData is used
Used to retrieve data
LinkedList is more efficient than ArrayList for frequent insert and delete operations, and the underlying layer uses bidirectional linked list storage
Vector: as an ancient implementation class of the List interface, the thread safety efficiency is low, and the underlying implementation is the same as ArrayList
5. Describe the approximate implementation of ArrayList source code, initial size, what is capacity expansion, and how to expand the source code

	//Add:
		ArrayList li = new ArrayList();
        		li.add(123);
        		li.add(456);
        		li.add("AA");
        		li.add(new String("Tom"));
        		li.add(123);
	//Delete
		li.remove(0);
	//Change:  
		li.set(1,"AA");
	//Check:
		li.get(1);

jdk1.7: The initial size of Object[] elementData is 10
jdk1. After 8, Object[] elementData is initialized to {} with an initial size of 0. When the add () method is called, an array with a length of 10 will be given and the data will be added to elementData
Capacity expansion: expand the length of Object[] elementData

//Determine the minimum length of the current required array and the size of the array length
	if (minCapacity - elementData.length > 0)
            		grow(minCapacity);//If the required minimum length is greater than the array length, expand the capacity
	}
	private void grow(int arg0) {
		int arg1 = this.elementData.length;//Current array length
		int arg2 = arg1 + (arg1 >> 1);//Expand to 1.5x (default)
		if (arg2 - arg0 < 0) {//Expand to twice the original
			arg2 = arg0;
		}
 
		if (arg2 - 2147483639 > 0) {
			arg2 = hugeCapacity(arg0);
		}
 		//Overwrite the original array with the new array
		//to update
		this.elementData = Arrays.copyOf(this.elementData, arg2);
 
	}

6. Describe the approximate implementation of the LinkedList source code, the initial size, what is capacity expansion, and how to expand the source code
The first and last attributes of Node type are declared internally, and the default value is null
LinkedList list=new LinkedList();
list.add(123); Encapsulating 123 into Node creates a Node object
Where: Node is defined as:

private static class Node<E> {
        			E item;
       				Node<E> next;
        			Node<E> prev;
 
        			Node(Node<E> prev, E element, Node<E> next) {
            			this.item = element;
            			this.next = next;
            			this.prev = prev;
       		 	}
    		}

7. Briefly describe the advantages and disadvantages of ArrayList and LinkedList
ArrayList is mainly used to implement class threads, which is unsafe and efficient. At the bottom, the array Object[] elementData is used
LinkedList is more efficient than ArrayList for frequent insert and delete operations, and the underlying layer uses bidirectional linked list storage
8. What is set, what are its characteristics, and what specific subclasses are there? Subclasses have their own functional differences
Features: unordered (not equal to randomly stored data, which is not added in the order of array index in the underlying array, but according to the hash value of the data)
Non repeatable: ensure that the added elements cannot return true when judged according to equals(), that is, only one of the same elements can be stored
HashSet: thread unsafe as the main implementation class of the Set interface; null values can be stored
LinkedHashSet: as a subclass of HashSet, when traversing its internal data, it can be traversed in the order of addition
LinkedHasdSet is a subclass of HashSet. While adding data, each data also maintains two references, recording the previous data and the next data of the data
For frequent traversal operations, linkedHashSet is more efficient than HashSet
TreeSet: you can sort by the specified attribute of the added object (the data put into TreeSet is the same attribute)
There are two sorting methods: natural sorting (implementing Comparable interface) and custom sorting (Comparator)

9. Briefly describe the steps of adding elements to HashSet (hashCode and equals)
Requirement: the class of data added to Set (mainly HashSet and linkedhashset) must override hashCode() and equals() methods
Requirement: the rewritten hashCode() and equals() should be consistent as much as possible. Equal objects must have equal hash codes.
Tip for rewriting two methods: the fields in the object used for the equals() method comparison should be used to calculate the hashCode value
To add element a to the HashSet, we first call the hashCode () method of the class where element a is located to calculate the hash value of element a
This hash value then calculates the storage position in the underlying array of the HashSet through some algorithm to determine whether there are elements in this position of the array
If there are no other elements at this location, the element is added successfully
If there are other elements in this position (or multiple elements are stored in a linked list), compare element a with element b
hash value of;
If the hash values are different, element a is added successfully
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
It is stored in a linked list
jdk7 element a is placed in the array and points to the original element
jdk8 the original element points to element a in the array
Conclusion: seven up and eight down
HashSet bottom layer: array + linked list structure.

//De duplication in list
public static List duplicateList(List list){
    HashSet set =new HashSet();
    set.addAll(list);
    return new ArrayList(set);
}
 
public static void main(String[] args) {
    List list=new ArrayList();
    list.add(new Integer(1));
    list.add(new Integer(2));
    list.add(new Integer(3));
    list.add(new Integer(1));
    //Note that if it is an object, you need to override hashCode() and equals()
    List list1 = duplicateList(list);
    Iterator iterator = list1.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

10. What are the basic operations of linkedhashset
LinkedHasdSet is a subclass of HashSet. While adding data, each data also maintains two references, recording this
Previous data and subsequent data of data
Advantages: for frequent traversal operations, linkedHashSet is more efficient than HashSet
11. Characteristics and basic operation of TreeSet, how to customize sorting
Ground floor: red black tree
1. The data added to TreeSet must be objects of the same class
2. Two sorting methods: natural sorting (implementing Comparable interface) and custom sorting (Comparator)
3. In natural sorting, the standard for comparing whether two objects are the same is: compareTo() returns 0, which is no longer equal()
4. In custom sorting, the criteria for comparing whether two objects are the same is: compare() returns 0, which is no longer equal()

Comparator com=new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            if (o1 instanceof User && o2 instanceof User){
                User user1=(User)o1;
                User user2=(User)o2;
                return Integer.compare(user1.getAge(), user2.getAge());
            }else {
                throw new RuntimeException("The input data types do not match!");
            }
        }
    };
    TreeSet set=new TreeSet(com);
    set.add(new User("Tom",12));
    set.add(new User("Jerry",33));
    set.add(new User("Jack",44));
    Iterator iterator = set.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
 
}

12. What are the characteristics of map, the commonly used implementation classes and the differences
Map: double column data, which is stored in the key value pair
Keys in Map: unordered and non repeatable. Use Set to store all keys - > the class where the key is located should override equals() and HashCode()
Value in Map: unordered and repeatable use Collection to store all values – the class where value is located should override equals ()
A key value pair: constitutes an Entry object
Entries in Map: unordered and unrepeatable. Use Set to store all entries
HashMap: as the main implementation class of Map, threads are unsafe and efficient, and null key value pairs are stored
LinkedHashMap: ensure that the map elements can be traversed in the order of addition.
Reason: on the basis of 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
Bottom layer: array + linked list before jdk 7
jdk8 array + linked list + red black tree
TreeMap: store ordered key value pairs to ensure sorting according to the added key value pairs to realize sorting traversal, which is considered at this time
Natural sorting and customized sorting of key s
Ground floor: red black tree
Hashtable: as an ancient implementation class, thread safety efficiency is low and null key value pairs cannot be stored
Properties are commonly used to handle configuration files. Both key and value are string types

Interview questions:
1. Underlying implementation principle of HashMap:
Array + linked list before jdk 7
jdk8 array + linked list + red black tree
2. Similarities and differences between HashMap and Hashtable:
HashMap, as the main implementation class of Map, has unsafe threads and high efficiency. It stores null key value pairs
Hashtable: as an ancient implementation class, thread safety efficiency is low and null key value pairs cannot be stored
13. Common methods and basic operations of HashMap (addition, deletion, modification, query, traversal of elements, etc.)
Add, delete and modify:
Object put(Object key,Object value):
Add (or modify) the specified key value to the current map object
void putAll(Map m): store all key value pairs in m into the current map
Object remove(Object key): removes the key value pair of the specified key and returns value
void clear(): clear all data in the current map
Operation of element query:
Object get(Object key): get the value corresponding to the specified key
boolean containsKey(Object key): whether the specified key is included
boolean containsValue(Object value): whether the specified value is included
int size(): returns the number of key value pairs in the map
boolean isEmpty(): judge whether the current map is empty
boolean equals(Object obj): judge whether the current map and parameter object obj are equal
Method of metaview operation:
Set keySet(): returns the set set composed of all keys
Collection values(): returns the collection collection composed of all values
Set entrySet(): returns the set set composed of all key value pairs
Practical operation:

HashMap map = new HashMap();
        //add to
        map.put(123, "AA");
        map.put(234, "BB");
        map.put(345, "CC");
        //add to
        HashMap map1 = new HashMap();
        map1.put(111, "wowowo");
        map1.put(123, "MM");
//query
        System.out.println(map1.get(111));
        //modify
        map1.putAll(map);
        //delete
        Object o = map1.remove(123);
        //clear
        map.clear();//The underlying array is still there, but the data is empty, so the map is still there
        System.out.println(map.size());
        System.out.println(o);
        System.out.println(map);
        System.out.println(map1);
//keySet() traverses all key sets
        Set set = map.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
//            System.out.println(map.get(iterator.next()));
            System.out.println(iterator.next());
        }
//Traverse all values sets
        Collection values = map.values();
        Iterator iterator1 = values.iterator();
        while (iterator1.hasNext()) {
            System.out.println(iterator1.next());
        }
//entrySet() traverses all key values in the collection
        Set set1 = map.entrySet();
        Iterator i1 = set1.iterator();
        while (i1.hasNext()) {
            Map.Entry aa=(Map.Entry)i1.next();
            System.out.println(aa.getKey()+"--->"+aa.getValue());
        }

13. Briefly describe the underlying implementation principle of HashMap and the difference between hashSet and HashMap.
jdk7 as an example:
HashMap map=new HashMap();
After instantiation, the bottom layer creates a one-dimensional array Entry[] table with a length of 16
... may have performed put more than once
map.put(key1,value1);
First, we call HashCode () of the class where key1 is located to calculate the hash value of key1. After some algorithm, the hash value is stored in the Entry array. If the data in this position is empty, key1-value1 is added successfully
Case 1

If the data in this location 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.

Case 2

If the hash value of key1 is the same as the hash value of the existing data, continue the comparison, and call the equals () method of the class where key1 is located. The comparison returns false
Key1-value1 added successfully. Return true and replace the same key value value with key1-value1

Case 3

Add: with regard to cases 2 and 3, key1-value1 and the original data are stored in a linked list, and capacity expansion will be involved in the process of continuous addition
When the critical value is exceeded (and the location to be stored is not empty), expand the capacity to twice the original and copy the original data

jdk8 is different from jdk7 in the underlying implementation
1.new HashMap(): the underlying layer does not create an array with a length of 16
2.jdk8 the underlying array is Node [] instead of Entry []
3. When the put () method is called for the first time, the underlying layer creates an array with a length of 16
4. The underlying structure of JDK7 is only array + linked list. The underlying structure of jdk8 is array + linked list + red black tree
When the number of elements at an index position of the array in the form of linked list is > 8 and the current array length is > 64
At this time, all data at this index position is stored in red black tree instead
DEFAULT_ INITIAL_ Capability: default capacity of HashMap, 16
DEFAULT_LOAD_FACTOR: HashMap default load factor: 0.75
threshold: critical value of expansion: 16 * 0.75 = 12
TREEIFY_THRESHOLD =: if the length of the linked list in the Bucket is greater than the default value, it will be converted into a red black tree: 8
MIN_ TREEIFY_ Capability: the minimum hash table capacity when nodes of the same kind are trealized
Differences between and HashSet:
Failed to add the same element in HashSet
When HashMap the same element, the new element will overwrite the original element

14. Briefly describe the underlying implementation principle of LinkedHashMap
HashMap subclass
Internal class Entry
For frequent traversal

static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;//Be able to record the order in which elements are added
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }

15. How to add elements in treemap
TreeMap:
Adding key values to TreeMap requires that the key must be an object created by the same class
Because you want to sort by key:

Natural sorting implements Comparable interface;

// Custom sorting:
public void TreeSetTest(){
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User1 && o2 instanceof User1){
                    User1 user1=(User1)o1;
                    User1 user11=(User1)o2;
                    return Integer.compare(user1.getId(), user11.getId());
                }
                throw new RuntimeException("Inconsistent input type");
            }
        });
        User1 u1=new User1("wowo1",12);
        User1 u2=new User1("wowo2",13);
        User1 u3=new User1("wowo3",14);
        User1 u4=new User1("wowo4",15);
        map.put(u1, 78);
        map.put(u2, 88);
        map.put(u3, 98);
        map.put(u4, 89);
        //ergodic
        Set set = map.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Object o = iterator.next();
            Map.Entry entry=(Map.Entry)o;
            System.out.println(entry.getKey()+"----"+entry.getValue());
        }
 
    }

16. Common methods of collections tool class

collections is a tool class that operates on lists, maps, and sets
Interview question: the difference between Collection and Collections
Collection is an interface for creating collections. Collections is a tool class for manipulating collections
Common methods:
Reverse (list): reverse the order of the elements in the list shuffle(list): randomly sort the elements of the list set
sort(list): sort the elements of the specified List set in ascending order according to the natural sorting 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 collection
frequenty(collection,Object); Returns the number of occurrences of the specified element in the specified collection
copy(list desc,list src) desc is the set to be copied and src is the set to be copied
Note: desc length must be equal to src length

ArrayList list = new ArrayList();
        list.add(1);
        list.add(3);
        list.add(5);
        list.add(2);
        List desc=Arrays.asList(new Object[list.size()]);
        Collections.copy(desc, list);
        System.out.println(desc);

The synchronizedList() method in the Collections tool class converts the list to thread safe
The synchronizedHashMap() method converts the map to thread safe
//ArrayList thread is unsafe
//Use the Collections tool class to call synchronizedList() to convert to thread safe
List list1 = Collections.synchronizedList(list);
//list1 thread safe

Topics: Java Interview