The difference between ArrayList and Vector
Both classes implement the List interface (the List interface inherits the Collection interface), they are both Ordered sets, that is, the positions of the elements stored in the two sets are in order, which is equivalent to a dynamic array. We can later take out an element according to the position index number, and the data in it is allowed to be repeated. . (Recommended study: java interview questions)
This is the biggest difference from collections such as HashSet. Collections such as HashSet cannot retrieve elements by index number, nor do they allow duplicate elements.
The difference between ArrayList and Vector mainly includes two aspects: .
(1) Synchronicity:
Vector is thread-safe, that is It is said that its methods are thread synchronized, while ArrayList is thread-unsafe and its methods are thread-asynchronous.
If only one thread will access the collection, it is best to use ArrayList, because it does not consider thread safety and will be more efficient; if multiple threads will access the collection, it is best to use Vector , because we don’t need to think about and write thread-safe code ourselves.
(2) Data growth:
ArrayList and Vector both have an initial capacity. When the number of elements stored in them exceeds the capacity, ArrayList and Vector need to be increased. Each time you want to increase the storage space, you don’t just add one storage unit, but add multiple storage units. The number of storage units added each time must achieve a certain balance between memory space utilization and program efficiency. .
Vector grows by twice its original size by default, while ArrayList’s growth strategy is not clearly specified in the document (from the source code, it is seen that it grows by 1.5 times its original size).
Both ArrayList and Vector can set the initial space size, and Vector can also set the growth space size, while ArrayList does not provide a method for setting the growth space.
Summary: Vector increases by twice its original size, and ArrayList increases by 0.5 times its original size.
The difference between HashMap and Hashtable
HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation). They both complete the Map interface, mainly The difference is that HashMap allows empty (null) key values ??(key). Due to non-thread safety, the efficiency is higher than Hashtable when only one thread accesses it.
HashMap allows null to be used as the key or value of an entry, but Hashtable does not.
HashMap has removed the contains method of Hashtable and changed it to containsvalue and containsKey. Because the contains method is easily misleading.
Hashtable inherits from the Dictionary class, and HashMap is an implementation of the Map interface introduced in Java 1.2.
The biggest difference is that Hashtable's method is Synchronized, but HashMap is not. When multiple threads access Hashtable, you do not need to synchronize its methods yourself, while HashMap must provide synchronization for it.
Regarding HashMap and HashTable, there are mainly three aspects.
1. Historical reasons: Hashtable is based on the old Dictionary class, and HashMap is an implementation of the Map interface introduced in Java 1.2
2. Synchronicity: Hashtable is thread-safe , that is to say, it is synchronous, while HashMap is an insecure online program and is not synchronous
3. Value: Only HashMap allows you to use a null value as the key or value of a table entry
What is the difference between List and Map?
One is a collection that stores single-column data, and the other is a collection that stores double-column data such as keys and values. The data stored in List is order, and allows duplication; the data stored in the Map is not in order, its keys cannot be repeated, and its values ??can be repeated.
Do List, Set, and Map inherit from the Collection interface?
List, Set is, but Map is not
List, Map, Set What are the characteristics of each of the three interfaces when accessing elements?
(This type of question compares the level of the test, in two aspects: one is to truly understand the content, and the other is to have strong summary and presentation skills.)
First of all, List and Set are similar. They are both collections of single-column elements, so they have a common parent interface called Collection.
Duplicate elements are not allowed in Set, that is, there cannot be two equal (note, not just the same) objects. That is, assuming that there is an A object in the Set collection, now I want to add another object to the Set collection. Store a B object, but if the B object is equal to the A object, the B object cannot be stored.
So, the add method of the Set collection has a boolean return value. When there is no element in the set, and the add method can successfully add the element, it will return true. When the set contains an element When equals equals elements, the add method cannot add the element at this time, and the return result is false. When Set takes elements, you cannot specify which number to take. You can only get all the elements through the Iterator interface, and then iterate through each element one by one.
List represents a collection in sequence. Note that it is not sorted by age, size, price, etc. When we call the add(Obje) method multiple times, the objects added each time are sorted in the order of first come, first served, just like the queue order for buying tickets at a train station.
Sometimes, you can also jump in the queue, that is, call the add(intindex,Obj e) method to specify the storage location of the current object in the collection.
An object can be stored repeatedly in the List. Each time the add method is called, the object is inserted into the collection once. In fact, the object itself is not stored in the collection, but in the collection. An index variable is used to point to this object. When this object is added multiple times, it is equivalent to multiple indexes in the collection pointing to this object.
In addition to using the Iterator interface to obtain all elements of List and then iterating through each element one by one, you can also call get(index i) to clearly indicate which number to retrieve.
Map is different from List and Set. It is a double-column collection, which has 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. Duplicate keys cannot be stored. The duplication rule is also based on equals comparison. The corresponding value can be obtained 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, the combination of all values, and the collection of Map.Entry objects composed of key and value.
List holds elements in a specific order and may have duplicate elements. Set cannot have duplicate elements and is sorted internally. Map saves key-value values, and value can have multiple values.
Tell me about the storage performance and characteristics of ArrayList, Vector, and LinkedList
Both ArrayList and Vector use arrays to store data. The number of elements in this array is greater than the actual stored data. In order to add and insert elements, they all allow elements to be indexed directly by serial number, but inserting elements involves memory operations such as array element movement, so indexing data is fast but inserting data is slow. Vector usually has better performance due to its use of the synchronized method (thread safety). Worse than ArrayList.
LinkedList uses a doubly linked list for storage. Indexing data by serial number requires forward or backward traversal, and the index becomes slower. However, when inserting data, you only need to record the before and after items of this item, so insert Faster.
LinkedList is also thread-unsafe. LinkedList provides some methods so that LinkedList can be used as a stack and queue.
Remove duplicate elements from a Vector set
Vector newVector = new Vector(); For (int i=0;i<vector.size();i++) { Object obj = vector.get(i); if(!newVector.contains(obj); newVector.add(obj); }
There is also a simple way to use Set that does not allow duplicate elements:
HashSetset = new HashSet(vector);
The difference between Collection and Collections.
Collection is the superior interface of the collection class. The interfaces that inherit it mainly include Set and List.
Collections is a helper class for the collection class. It provides a series of static method implementations. Search, sort, thread-safe and other operations on various collections.
The elements in Set cannot be repeated, so what method is used to distinguish whether they are repeated or not? Should you use == or equals()? What is the difference between them?
The elements in the Set cannot be repeated. Whether the elements are repeated or not is determined using the equals() method. The difference between
== and equal is also a question that has failed in the test. Let me talk about it here:
== operator is specially used to compare whether the values ????of two variables are equal. That is, it is used to compare whether the values ??stored in the memory corresponding to the variables are the same. To compare whether two basic types of data or two reference variables are equal, you can only use the == operator.
The equals method is used to compare whether the contents of two independent objects are the same, just like comparing whether the appearance of two people is the same. The two objects it compares are independent.
For example: two new statements create two objects, and then use the two variables a/b to point to one of the objects respectively. These are two different objects, and their first addresses are different. That is, the values ??stored in a and b are different, so the expression a==b will return false, and the contents of the two objects are the same, so the expression a.equals(b) will return true .
What collection classes do you know? Main method?
The most commonly used collection classes are List and Map. Specific implementations of List include ArrayList and Vector, which are variable-sized lists and are more suitable for constructing, storing, and manipulating element lists of any type of object. List is suitable for accessing elements by numerical index.
Map provides a more general element storage method. The Map collection class is used to store pairs of elements (called "keys" and "values"), where each key maps to a value.
They all have methods of adding, deleting, modifying and checking.
For set, the general methods are add, remove, contains, etc.
For map, the general methods are put, remove, contains, etc.
The List class will have get( int index) because it can take elements in order, and there is no method like get(int index) in the set class. Both List and set can iterate out all elements. When iterating, you must first obtain an iterator object. Therefore, both the set and list classes have an iterator method for returning the iterator object.
map can return three collections, one returns a collection of all keys, the other returns a collection of all values, and the other returns a collection of EntrySet objects composed of keys and values. Map also has a get method and parameters. It is the key, and the return value is the value corresponding to the key. This is free play, and it is not the ability to test the method. There will be prompts during the programming process. Just talk about the usage based on the differences between the three.
The above is the detailed content of java collection interview questions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.
