1. What are the basic interfaces of the Java Collection Class framework?
Refer to the answer
The collection class interface specifies a set of objects called elements. Each concrete implementation class of the collection class interface can choose to save and sort elements in its own way. Some collection classes allow duplicate keys, some do not. Java collection classes provide a well-designed set of interfaces and classes that support manipulation of a set of objects. The most basic interface in Java Collection classes is: Collection: represents a group of objects, each of which is a child element. Set: A Collection that does not contain repeating elements. List: An ordered collection that can contain repeating elements. Map: An object that maps keys to values. Keys cannot be duplicated.
2. Why does the collection class not implement Cloneable and Serializable interfaces?
Refer to the answer
The semantics and meanings of cloning or serialization are implementation-specific. Therefore, it is up to the implementation of the collection class to decide how it is cloned or serialized.
3. What is an Iterator?
Refer to the answer
The Iterator interface provides many methods for iterating over collection elements. Each collection class contains \ that can return an iterator instance
Iterative methods. Iterators can delete elements of the underlying collection during iteration, but cannot directly call elements of the collection
Remove (Object Obj) to remove, which can be removed by the remove() method of the iterator.
4. What is the difference between Iterator and ListIterator?
Refer to the answer
The differences are listed below: Iterator can be used to iterate over sets and lists, while ListIterator can only be used to iterate over lists. Iterator can traverse only forward over sets; ListIterator can traverse both forward and backward. ListIterator implements the Iterator interface and includes other functions such as adding elements, replacing elements, retrieving the previous and next element indexes, and so on.
5. What is the difference between fail-fast and fail-safe?
Refer to the answer
Iterator’s security failure is based on making a copy of the underlying collection, so it is not affected by changes made on the source collection. All collection classes under the java.util package fail quickly, while all classes under the java.util. Concurrent package fail safely. Rapid failure of the iterator will throw ConcurrentModificationException, iterators and safety failure never throw this exception.
6. How does Java HashMap work?
Refer to the answer
A HashMap in Java stores elements as key-value pairs. A HashMap requires a hash function that uses the hashCode() and equals() methods to add and retrieve elements to/from the collection. When the put() method is called, the HashMap computes the hash value of the key and stores the key-value pair on the appropriate index in the collection. If the key already exists, the value will be updated to the new value. Some of the important features of HashMap are its capacity, load factor and threshold resizing.
7. Why are the hashCode() and equals() methods important?
Refer to the answer
Java’s HashMap uses the hashCode() and equals() methods to determine the index of key-value pairs, which are also used when retrieving values based on keys. If these two methods are not implemented correctly, two different keys may have the same hash value and, therefore, may be considered equal by the collection. Also, these two methods are used to find duplicate elements. So the implementation of these two methods is critical to the accuracy and correctness of the HashMap.
8. What is the difference between HashMap and Hashtable?
Refer to the answer
Both HashMap and Hashtable implement the Map interface, so many features are very similar. However, they differ in the following way: HashMap allows keys and values to be null, while Hashtable does not. Hashtable is synchronous, HashMap is not. Therefore, HashMap is better suited for single-threaded environments, while Hashtable is better suited for multi-threaded environments. A HashMap provides a set of keys to which iterations can be applied, so a HashMap fails quickly. Hashtable, on the other hand, provides Enumeration of keys. Hashtable is generally thought of as a legacy class.
Application scenario analysis:
HashMap and HashTable:HashMap removes the contains methods of HashTable, but adds containsValue() and containsKey() methods. HashTable is synchronous, whereas HashMap is asynchronous and is more efficient than HashTable. A HashMap allows empty key values, whereas a HashTable does not.
HashMap: Used to insert, delete, and locate elements in a Map.
Treemap: Applies to traversing keys in natural or custom order.
What’s the difference between an Array and an ArrayList? When should you use Array instead of ArrayList?
Refer to the answer
The differences between Array and ArrayList are listed below: Array can contain both primitive types and object types, whereas ArrayList can contain only object types. The Array size is fixed, whereas the size of an ArrayList changes dynamically. ArrayList provides more methods and features, such as addAll(), removeAll(), iterator(), and so on. For primitive type data, collections use automatic boxing to reduce the coding effort. However, this approach is relatively slow when dealing with basic data types of fixed size.
10. What’s the difference between ArrayList and LinkedList?
Refer to the answer
ArrayList and LinkedList both implement the List interface, and they differ in the following ways: ArrayList is an index-based data interface, and its underlying layer is arrays. It can randomly access elements in order of O(1) time. In contrast, LinkedList stores its data as a list of elements, each linked to its preceding and following element, in which case the time to find an element is O(n). Compared to ArrayList, LinkedList inserts, adds, and deletes are much faster because there is no need to recalculate or update the index as an array does when an element is added anywhere in the collection. LinkedList takes up more memory than ArrayList because LinkedList stores two references for each node, one to the previous element and one to the next. Also see ArrayList vs. LinkedList.
Application scenario analysis:
ArrayList is used when data needs to be accessed, and LinkedList is used when data needs to be added and deleted multiple times.
What are the Comparable and Comparator interfaces for? List the differences.
Refer to the answer
Java provides a Comparable interface that contains only a compareTo() method. This method can sort two objects individually. Specifically, it returns negative numbers, 0, and positive numbers to indicate that an existing object is less than, equal to, or greater than the input object. Java provides a Comparator interface that contains the compare() and equals() methods. The compare() method is used to sort two input arguments, returning a negative number, 0, with a positive number indicating that the first argument is less than, equal to, or greater than the second argument. The equals() method takes an object as a parameter that determines whether the input parameters are equal to the comparator. This method returns true only if the input parameter is a comparator and the sorting result of the input parameter is the same as the current comparator.
What is a Java Priority Queue?
Refer to the answer
PriorityQueue is an unbounded queue based on the priority heap whose elements are sorted in natural order. At creation time, we can provide it with a comparator that sorts the elements. Priorityqueues do not allow null values because they have no natural order, or they do not have any associated comparators. Finally, PriorityQueue is not thread-safe, with order (log(n)) in and out of queues.
13. Do you know the big-o notation? Can you give examples of different data structures?
Refer to the answer
The big O notation describes the size or asymptotically upper bound of the algorithm as the number of elements in the data structure increases. The big O notation can also be used to describe other behaviors, such as memory consumption. Because collection classes are really data structures, we generally use the big O notation to choose the best implementation based on time, memory, and performance. The big O notation gives a good indication of the performance of large amounts of data.
14. How to weigh whether to use an unordered array or an ordered array?
Refer to the answer
The biggest advantage of ordered arrays is that the time to find them is order log n, while unordered arrays are order n. The disadvantage of ordered arrays is that the insertion time is O(n), because elements with large values need to be moved back to make room for new elements. In contrast, the insertion time complexity of an unordered array is constant O(1).
15. What are the best practices for Java collection class frameworks?
Refer to the answer
Choosing the right type of collection to use for your application is critical to performance. For example, if the number of elements is fixed and can be known in advance, you should use Array instead of ArrayList. Some collection classes allow you to specify initial capacity. Therefore, if we can estimate the number of stored elements, we can set the initial capacity to avoid recalculating the hash value or expanding the capacity. Generics are always used for reasons of type safety, readability, and robustness. Also, you can avoid classcastExceptions at runtime by using generics. Using immutable classes provided by the JDK as keys for maps avoids implementing the hashCode() and equals() methods for our own classes. Interfaces are better than implementations when programming. Return a collection or array of length 0 if the underlying collection is actually empty. Do not return NULL.
16. What are the differences between an Enumeration interface and an Iterator interface?
Refer to the answer
Enumeration is twice as fast as Iterator and uses less memory. However, Iterator is far safer than Enumeration because no other thread can modify the objects in the collection being iterated over. At the same time, Iterator allows the caller to delete elements from the underlying collection, which is not possible with Enumeration.
17. What’s the difference between HashSet and TreeSet?
Refer to the answer
1.TreeSet is implemented by binary tree (tree data structure of red-black tree). Data in TreeSet is automatically sorted and null values are not allowed.
2. A HashSet is implemented by a hash table. The data in a HashSet is unordered and can be put into a NULL, but only one NULL.
3. A HashSet requires that objects that have been put into a HashSet must implement the HashCode() method. Objects that have been put into a HashSet are identified by a HashCode, while String objects that have the same content have the same HashCode. But objects of the same class can fit into different instances.
A HashSet is implemented by a hash table and, therefore, its elements are unordered. The time complexity of the add(), remove(), and contains() methods is O(1). TreeSet, on the other hand, is implemented by a tree structure in which the elements are ordered. Therefore, the time complexity of the add(), remove(), and contains() methods is O(logn).
Application scenario analysis:
A HashSet is implemented based on a Hash algorithm and generally performs better than TreeSet. For sets designed for quick lookups, we should usually use hashSets, and TreeSet is used only when we need sorting capabilities.
18, What are the specific implementation classes of collection framework, list, map and set? What are the differences?
Refer to the answer
1. List and Set inherit from Collection interface, Map does not;
2. List features: elements can be placed in order, and elements can be repeated;
The position of the elements in a Set is determined by the element’s HashCode. Objects added to a Set must define equals().
In addition, list supports for loop, that is, traversal by subscript, can also use iterators, but set can only use iteration, because it is unordered, can not use subscript to get the desired value).
3.Set and List
Set: It is inefficient to retrieve elements, but efficient to delete and insert elements. Insert and delete elements do not change their positions.
List: Like an array, a List can grow dynamically. It is efficient to find elements, but inefficient to insert and delete elements, because it causes other elements to change positions.
4. Map is suitable for storing key-value pair data.
5. Thread-safe and non-thread-safe collection classes
LinkedList, ArrayList, and HashSet are thread-safe; Vector is thread-safe;
HashMap is thread-safe, HashTable is thread-safe;
StringBuilder is not thread-safe, StringBuffer is thread-safe.
19. Differences between ArrayList and Vector and applicable scenarios
Refer to the answer
ArrayList has three constructors:
Public ArrayList(int initialCapacity)// constructs an empty list with a specified initialCapacity. Public ArrayList()// Constructs an empty list of initial capacity 10. public ArrayList(Collection<? Extends E> c)// Constructs a list of elements for the specified collectionCopy the code
A Vector has four constructors:
Public Vector() // Constructs an empty Vector with the specified initial capacity and a capacity increment equal to zero. Public Vector(int initialCapacity) // Constructs an empty Vector with the size of its internal data array, whose standard capacity increment is zero. public Vector(Collection<? Extends E> c) extends E> c) extends E> c) extends E> c) extends E> c) extends E> c) extends E> c CapacityIncrement constructs an empty vector with the specified initial capacity and capacityIncrementCopy the code
ArrayList and Vector are both implemented using arrays, with three main differences:
1).Vector is multithread safe. Thread-safe means that multiple threads accessing the same code will not produce uncertain results. ArrayList does not. As can be seen from the source code, many of the methods in the Vector class are modified by synchronized, so that Vector cannot compare with ArrayList in efficiency.
2). Both classes use linear continuous space to store elements, but when space is insufficient, the two classes increase in different ways.
3).Vector can set growth factors, whereas ArrayList cannot.
4).Vector is an old dynamic array that is thread synchronized. It is inefficient and generally deprecated.
Applicable scenarios:
1.Vector is thread-synchronous, so it is thread-safe, whereas ArrayList is thread-asynchronous and unsafe. Without regard to thread safety, ArrayList is generally more efficient.
2. If the number of elements in the collection is greater than the size of the current array, using a Vector has certain advantages when using a large amount of data in the collection.
\
class A {} class B extends A {} class C extends A {} class D extends B {} Which four statements are true ? \
-
The type List<A>is assignable to List. Copy the code
-
The type List<B>is assignable to List<A>. Copy the code
-
The type List<Object>is assignable to List<? >.Copy the code
-
The type List<D>is assignable to List<? extends B>.Copy the code
-
The type List<? extends A>is assignable to List<A>.Copy the code
-
The type List<Object>is assignable to any List reference. Copy the code
-
The type List<? extends B>is assignable to List<? extends A>.Copy the code
View the correct options
A, C, D, G
1. Only read Angle brackets!! Clarify the concepts of point and scope
List<A>,List<B>,List<Object>
3. If there is a question mark inside Angle brackets, it represents a range, <? Extends A> represents the range that is less than or equal to A, <? Super A> represents the range greater than or equal to A, <? > represents the full range
4. All points in Angle brackets are incorrectly assigned to each other, unless they are identical points
5. Angle brackets small range to large range, yes, large range to small range, wrong. If a point is contained within a range, it can be assigned; otherwise, it cannot be assigned
6. List<? > and List are equal, both representing the maximum range
———————————————————————————-
7. Add: List is both a point and a range
Below post code :(originally used Eclipse screenshots, the result seems to be a Bug website, can not upload the map o(╯□╰)
1234567891011121314151617 | public static void main(String[] args) {`` ``List<A> a; `` ``List list; `` ``list = a; '//A Yes, because List is List<? `` ``List<B> B; `` ``a = b; `` ``List<? > qm; `` ``List<Object> o; `` ``qm = o; ` ` / / C: yes, the List <? > represents the largest range, List<Object> is just a point that must be included `` ``List<D> D; `` ``List<? ``extends B> downB; `` ``downB = d; ` ` / / D, the List <? Extends B> represents ranges of less than or equal to B, and List<D> is a point where `` ``List<? ``extends A> downA; `` ``a = downA; '// range cannot be assigned to point `` ``a = o; List<Object> is just a dot `` ``downA = downB; //G yes, ranges less than or equal to A include ranges less than or equal to B, because B is inherently less than A, A subclass of A `` ``} ' |
The general idea is that Java arrays are covariant, while Java collections are not;
What does that mean? Let me give you a few examples:
If we pass in a Dog d object, the compiler will not give an error. Fun (Animal Animal)
2. If we have fun (Animal[] animals), if we pass an array like Dog[] dogs, the compiler will not give an error.
Fun (List<Animal> Animal). If we pass a List< Dog> Dog, the compiler will give an error.
So what to do? We can change the generics to fun (List <? Extends Animal>), and then when we pass in a List <Dog> Dog collection, the compiler doesn’t get an error. So you can pass in a List that contains subclasses of Animal.
In Java, what is wrong with the description of the HashMap class?
-
The order of elements in a HashMap is guaranteedCopy the code
-
HashMap allows null to be used as a valueCopy the code
-
HashMap allows null to be used as a keyCopy the code
-
A HashMap stores data in key/worth formCopy the code
A
The bottom layer of HashMap is realized by array plus linked list. For each key value, it needs to calculate the hash value, and then determine the order through the hash value. It is not stored according to the order of joining, so it can be considered as unordered, but whether it is ordered or unordered, it has its own order. So A fault.
In the beginning, there was a Hashtable, which did not allow null keys and values. However, in the end, there was a Hashtable, which did not allow null keys and values. if(key = null) {putForNullKey(value); };
Maps are stored in the form of key/value pairs
In the JDK1.5 environment, there are four statements:
Integer i01 = ``59``;
int
i02 = ``59``;
Integer i03 =Integer.valueOf(``59``);
Integer I04 = new Integer(59).
The following output is false:
C
System.out.println(i01== i02);
Copy the code
System.out.println(i01== i03);
Copy the code
System.out.println(i03== i04);
Copy the code
System.out.println(i02== i04);
Copy the code
When Integer i01=59, valueOf of Integer is called,
12345 | ``public static Integer valueOf(``int i) {`` ``assert IntegerCache.high>= ``127``; `` ``if (i >= IntegerCache.low&& i <= IntegerCache.high)`` ``return IntegerCache.cache[i+ (-IntegerCache.low)]; `` ``return new Integer(i); } |
This method returns an Integer object, which is treated as a check to determine whether the current value of I differs between [-128,127] and whether the object exists in IntegerCache. If so, the reference is returned, otherwise a new object is created.
In this case, because it’s the first time we’re running, we don’t have 59, so we just create a new object.
Int i02=59, which is a basic type, stored on the stack.
Integer i03 =Integer.valueOf(59); Because the object already exists in IntegerCache, the reference is returned directly.
Integer i04 = new Integer(59); Create a new object directly.
System. out .println(i01== i02); I01 is an Integer object, i02 is an int, and we’re not comparing addresses, we’re comparing values. Integer is automatically unpacked into ints and values are compared. So, true.
System. out .println(i01== i03); True because i03 returns a reference to i01.
System. out .println(i03==i04); Since i04 is a recreated object, i03 and i04 point to different objects, so the comparison result is false.
System. out .println(i02== i04); Since I02 is a basic type, i04 will be automatically unpacked for value comparison. Therefore, the result is true.