亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java JavaInterview questions java collection interview questions

java collection interview questions

Dec 02, 2019 pm 04:27 PM
java

java collection interview questions

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

See all articles