国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. What is a collection framework?
2. Collection interface
1. Specify the object type in the corresponding collection through generics
2.Collection common methods use
3. Map interface
Map common methods use
4、具體的實(shí)現(xiàn)類
Home Java javaTutorial What is the data structure of Java collection framework

What is the data structure of Java collection framework

May 28, 2023 pm 03:58 PM
java

    1. What is a collection framework?

    In Java, there is a set of ready-made data structures, such as sequence lists, linked lists, queues, stacks, priority queues, hash tables, etc., which are encapsulated into corresponding interfaces/classes for programmers to directly To use it, you only need to create the relevant objects to use, without the need to implement its internal structure.

    A collection is a data structure that stores and manages multiple elements, where these elements are placed in a single unit and can be processed through operations such as addition, deletion, modification, and query. For example, a set of playing cards (a collection of cards), an address book (a set of mapping relationships between names and phone numbers), etc. can be used as examples.

    The picture below is very important! ! ! You need to remember its commonly used interfaces and classes! !

    What is the data structure of Java collection framework

    What is the data structure of Java collection framework

    Because the map interface does not implement the Iterable interface, how to traverse the elements in it?

    		Map<Integer,String> map = new HashMap();
            map.put(1,"jack");
            map.put(2,"tom");
            Set<Map.Entry<Integer, String>> entries = map.entrySet();
            // 使用迭代器進(jìn)行遍歷 ,增強(qiáng) for同理
            Iterator<Map.Entry<Integer, String>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<Integer, String> entry =  iterator.next();
                System.out.println(entry.getKey() + " " + entry.getValue());
            }

    Taking HashMap as an example, you can call its entrySet() method to encapsulate each key-value pair in the map into a Map.Entry object. Because the Set interface is used to receive it, you can use iterators or for-each() to traverse, and each entry object has getKey() and getValue() methods to obtain the key value and value value respectively.

    Basic relationship (simplified version)

    What is the data structure of Java collection framework

    2. Collection interface

    is generally accepted by an interface or class that implements the Collection interface Specifically implement the object of the class, because as can be seen from the above figure, the Collection interface is the parent interface of a series of interfaces and classes. It has relatively few internally implemented methods, so it cannot call some common methods of subclasses.

    1. Specify the object type in the corresponding collection through generics

    Note: The type passed in here can only be a reference type. If it is a basic data type, its wrapper class should be used. Specify

    		Collection<String> collection1 = new ArrayList();
            collection1.add("haha");
            collection1.add("world");
            Collection<Integer> collection2 = new ArrayList();
            collection2.add(1);
            collection2.add(2);
            //collection2.add("hh");// 這里會(huì)報(bào)錯(cuò),不符合傳入的指定類型Integer

    2.Collection common methods use

    methodfunction
    void clear()Delete all elements in the collection
    boolean isEmpty()Determine whether the collection does not have any elements, Commonly known as the empty set
    boolean remove(Object e)If element e appears in the set, delete one of them
    boolean add(E e)Put element e into the collection
    int size()Return the number of elements in the collection
    Object[] toArray()Returns an array containing all elements in the collection

    Note: In the last Object[] toArray() method, an array of type Object[] is returned. The underlying method is: take out the elements in the collection one by one, convert them into Object objects, and store them in the array to be returned. , and finally returns an array of type Object[]. A type conversion exception is thrown when converting to a String[] array.

    What is the data structure of Java collection framework

    Because there is no guarantee that every element in the array is converted to String, but it is only forced to be converted into an array of type String[], so if you have to To convert, you need to first traverse the returned results, convert them to String type one by one, and finally assign them to an array of String[] type. It is not recommended to convert the array type as a whole in Java.

    		Object[] objects = collection1.toArray();
            String[] strings = new String[objects.length];
            for (int i = 0; i < objects.length; i++) {
                strings[i] = (String)objects[i];// 一個(gè)一個(gè)轉(zhuǎn),但是沒啥必要
            }

    3. Map interface

    stores data in the form of < k, v > key-value pairs. The key value here is unique, and each key value can correspond to its The corresponding value value. Different key values ??can correspond to the same value. HashMap: When storing elements, the internal hashCode function is called based on its key value to find the location where the element should be placed. Therefore, the elements in the hash table are not stored in the order in which they are stored.

    Map common methods use

    ##Set> entrySet()Return all key-value pairsboolean isEmpty()Determine whether it is emptyint size()Return the number of key-value pairs
    		HashMap<Integer, String> map = new HashMap<>();
    
            // put()
            map.put(1,"張飛");// 這里的 key 值唯一
            map.put(1,"宋江");// 如果二次插入的 key 值之前有,則替換其 value值
            map.put(2,"Jack");
            System.out.println(map);
    
            // get()
            String s1 = map.get(1);// 返回 宋江
            String s3 = map.getOrDefault(3,"三團(tuán)");// 未找到,返回 三團(tuán)
    
            // entrySet()
            // 該方法返回一個(gè) Set<Map.Entry<Integer, String>> 對(duì)象
            Set<Map.Entry<Integer, String>> entries = map.entrySet();
            for (Map.Entry<Integer, String> entry : entries) {
                // 通過 entry.getKey() 和 entry.getValue() 獲取每個(gè)entry對(duì)應(yīng)的 k, v值
                System.out.println(entry.getKey() + " " + entry.getValue());
            }

    What is the data structure of Java collection framework

    4、具體的實(shí)現(xiàn)類

    What is the data structure of Java collection framework

    The above is the detailed content of What is the data structure of Java collection framework. 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.

    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;

    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 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.

    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.

    Advanced Spring Data JPA for Java Developers Advanced Spring Data JPA for Java Developers Jul 31, 2025 am 07:54 AM

    The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used

    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

            MethodFunction
            V get(Object k)Find the corresponding v according to the specified k
            V getOrDefault(Object k, V defaultValue)According to the specified k Search for the corresponding v, if not found, return the default value
            V put(K key, V value)Put the specified k-v into the Map
            boolean containsKey(Object key)Judge whether it contains key
            boolean containsValue(Object value)Judge whether it contains value