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

Home Java Javagetting Started What are the commonly used collection classes in java

What are the commonly used collection classes in java

Dec 02, 2019 pm 05:04 PM
java Commonly used Collection class

What are the commonly used collection classes in java

1. Set collection

The main implementation classes are HashSet, TreeSet to store references to objects, which are not allowed Duplicate objects.

Example code:

public class SetTest {
    public static void main(String[] args) {      
    Set set=new HashSet();       //添加數(shù)據(jù)        
    set.add("abc");      
    set.add("cba");      
    set.add("abc");//故意重復(fù)      
    set.add(123);      
    set.add(true);        
    System.out.println("集合元素個數(shù):"+set.size());        //遍歷出集合中每一個元素       
    Iterator it=set.iterator();       
    while(it.hasNext()){         
        System.out.println(it.next());        
    }     
    }  
}

Judged by the equals() method of java. If you have special needs, you must overload the equals() method.

1.HashSet(), call the hashCode() method of the object, obtain the hash code, and then calculate the location of the object in the set. Determine whether there are duplicates by comparing the hash code with the equals() method. Therefore, if you overload the equals() method, you must also overload the hashCode() method.

Recommended video tutorials: java online learning

2.TreeSet(), inherits the ShortedSet interface, and can Sorting of objects in a collection. The default sorting method is natural sorting, but this method can only sort objects that implement the Comparable interface. This interface is implemented in Java for numerical and character objects such as Integer, Byte, Double, Character, and String.

If there is special sorting, you must overload the compareTo() method under this interface or construct a collection through the implementation class of the Comparator interface.

2. List collection

The main implementation classes are LinkedList and ArrayList. The former implements the linked list structure and the latter can represent variable sizes. array.

The characteristic of List is that it can store objects in a linear manner and allows the storage of duplicate objects. List can be sorted using the static method sort of the Collections class. sort(List list) natural sorting; sort(List listm, Comparator codddmparator)Customized sorting.

Example code:

List: linear collection interface, ordered;

ArrayList: dynamic array [variable length Dynamic array];

LinkedList: A collection of linked list structures.

  public class ListTest {
     //ArrayList     
     static void testOne(){      
     List list=new ArrayList();       //添加數(shù)據(jù)       
     list.add("abc");       
     list.add("cba");       
     list.add(123);       
     list.add(0,"fist");       //查看集合長度       
     System.out.println("存放"+list.size()+"個元素");       
     list.remove(0);//刪除第一個元素       //查看集合中是否包含cba       
     if(list.contains("cba")){        
     System.out.println("包含元素cba");    
     }         //取出集合中第二個元素       
     System.out.println("第二個元素是:"+list.get(1));         //取出集合中所有元素       
     for (int i = 0; i < list.size(); i++) {         
     System.out.println(list.get(i));      
     }     
     }       //LinkedList      
     static void testTwo(){      
     LinkedList list=new LinkedList();      //添加元素      
     list.add("aaaa");      
     list.add(123123);      
     list.addFirst("1111111");      
     list.addLast("2222222");      
     list.add("33333333");        
     System.out.println("元素個數(shù):"+list.size());      //取出第三個元素      
     System.out.println("第三個元素是:"+list.get(2));        //第一個元素      
     System.out.println("第一個元素:"+list.getFirst());      
     System.out.println("最后一個元素:"+list.getLast());        //刪除第一個元素      
     list.removeFirst();        
     for (Object object : list) {        
     System.out.println(object);      
     }     
     }      
     public static void main(String[] args) {      //testOne();      
     testTwo();     
     }  
     }

3. Map collection.

The main implementation classes are HashMap and TreeMap. Map does not require uniqueness for values, but requires uniqueness for keys. If an existing key is added, the original value object will be overwritten.

The HashMap class accesses key objects according to the hash algorithm. You can overload the equals() and hashCode() methods to compare keys, but they must be consistent. . TreeMap, can be sorted naturally, or a TreeMap can be constructed by passing the implementation class of Comparator.

Map: A collection of key-value pair storage structures, unordered.

Example code:

public class MapTest {
    public static void main(String[] args) {       //實例化一個集合對象       
    Map map=new HashMap();       //添加數(shù)據(jù)       
    map.put("P01", "zhangSan");       
    map.put("P02", "Lucy");       
    map.put("PSex", "男");       
    map.put("PAge", "39");       
    map.put("PAge", "22");//key,重復(fù)會被后面的覆蓋         //判斷是否有一個key為PSex       
    if(map.containsKey("PSex")){        
        System.out.println("存在");        
    }      
    System.out.println("集合大小:"+map.size());      
    System.out.println("輸出key為PAge的值:"+map.get("PAge"));        //遍歷出Map集合中所有數(shù)據(jù)      
    Iterator it=map.keySet().iterator();      
    while(it.hasNext()){      
        String key=it.next().toString();      
        System.out.println("key="+key+",value="+map.get(key));    
    }      
    /*      
    Set set=map.keySet();//取出map中所有的key并封裝到set集合中      
    Iterator it=set.iterator();      
    while(it.hasNext()){      
        String key=it.next().toString();      
        System.out.println("key="+key+",value="+map.get(key));    
    }      
    */    
    }  
    }

Recommended related articles and tutorials: java entry program

The above is the detailed content of What are the commonly used collection classes in java. 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
1502
276
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.

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

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles