Collection of classic Java interview questions (7)

1. Let’s talk about the difference between ArrayList and Vector
(more recommended interview questions: java interview questions)
1. Synchronicity: Vector is thread-safe. Use synchronized to achieve thread safety, while ArrayList is thread-unsafe. If only one thread will access the collection, it is best to use ArrayList because it does not consider Thread-safe, the efficiency will be higher;
If multiple threads will access the collection, it is best to use Vector, because we do not need to think about and write thread-safe code.
2. Data capacity growth: Both have an initial capacity size and use linear continuous storage space. When the number of stored elements exceeds the capacity, the storage space of both needs to be increased, and Vector grows. Double the original value, ArrayList increases by 0.5 times the original value.
2. Why is the ArrayList thread unsafe?
The operation of adding elements to the ArrayList is carried out in two steps, that is, the first step is to Store the elements to be added at the location of object[size]; in the second step, increase the value of size by 1.
Since this process is not guaranteed to be atomic in a multi-threaded environment, ArrayList is thread-unsafe in a multi-threaded environment.
(Related tutorial recommendations: java introductory tutorial)
3. What are the differences between HashMap, LinkedHashMap, and TreeMap?
1. HashMap is the most commonly used Map. It stores data according to the hashCode value of the key. Its value can be obtained directly according to the key, and has a very fast access speed. HashMap only allows the key of one record to be null, and does not allow the value of multiple records to be null.
HashMap does not support thread synchronization, that is, multiple threads can write HashMap at the same time at any time, which may lead to data inconsistency. If synchronization is required, you can use the Collections.synchronizedMap(HashMap map) method to make HashMap synchronized.
2. Hashtable is similar to HashMap, except that it does not allow the recorded keys or values to be empty; it supports thread synchronization, that is, only one thread can write to Hashtable at any time. However, this also leads to Hashtable will be slower when writing.
3. LinkedHashMap saves the insertion order of records. When traversing LinkedHashMap with Iteraor, the record obtained first must be inserted first. It will be slower than HashMap when traversing. Has all the features of HashMap.
4. TreeMap can sort the records it saves according to keys. The default is in ascending order. You can also specify a sorting comparator. When using Iteraor to traverse a TreeMap, the records obtained are sorted. The keys and values of TreeMap cannot be empty.
4. How to remove duplicate elements from a Vector collection?
Use the Vector.contains() method to determine whether the element is included. If it is not included, add it to a new collection. It is suitable for cases where the data is small.
There is also a simple way to traverse the Vector and put in set, SortdSet, HashSet, etc.
(Video tutorial recommendation: java video tutorial)
5. What are the characteristics of the three interfaces List, Map, and Set when accessing elements? ?
1. Duplicate elements are not allowed in Set
Save elements:
The add method has a boolean return value. When there is no such element in the set, For an element, when the add method can successfully add the element, it returns true; when the set contains an element equal to an element equals, the add method cannot add the element at this time, and the return result is false.
Get elements:
There is no way to tell which number to get. You can only get all the elements through the Iterator interface, and then iterate through each element one by one.
2. List represents a sequential collection
Storing elements:
When the add(Object) method is called multiple times, the objects added each time are sorted in the order of first come, first served. , you can also jump in the queue, that is, call the add(int index,Object) method to specify the storage location of the current object in the collection.
Getting elements:
Method 1: The Iterator interface gets all the elements and iterates through each element one by one.
Method 2: Call get(index i) to clearly indicate which index to take. Use this interface to precisely control the insertion position of each element. Users can access elements in the List using the index (the position of the element in the List, similar to an array subscript), which is similar to Java's array.
3. Map is a double-column collection
Storing elements:
Use the put method, put(obj key, obj value). Each time you store, you need to store one For key/value, duplicate keys cannot be stored. The duplication rule is also based on equals comparison.
Get elements:
Use the get(Object key) method to obtain the corresponding value based on the key. You can also get a collection of all keys, a collection of all values, and a collection of Map.Entry objects composed of keys and values.
List holds elements in a specific order and can have duplicate elements; Set cannot have duplicate elements and is sorted internally; Map saves key-value values, and value can be multi-valued.
The above is the detailed content of Collection of classic Java interview questions (7). 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)
What is a deadlock in Java and how can you prevent it?
Aug 23, 2025 pm 12:55 PM
AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree
How to use Optional in Java?
Aug 22, 2025 am 10:27 AM
UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor
Java Persistence with Spring Data JPA and Hibernate
Aug 22, 2025 am 07:52 AM
The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona
Java Cryptography Architecture (JCA) for Secure Coding
Aug 23, 2025 pm 01:20 PM
Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time
LOL Game Settings Not Saving After Closing [FIXED]
Aug 24, 2025 am 03:17 AM
IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.
How to use the Pattern and Matcher classes in Java?
Aug 22, 2025 am 09:57 AM
The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient
Edit bookmarks in chrome
Aug 27, 2025 am 12:03 AM
Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.
'Java is not recognized' Error in CMD [3 Simple Steps]
Aug 23, 2025 am 01:50 AM
IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.


