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();       //添加数据        
    set.add("abc");      
    set.add("cba");      
    set.add("abc");//故意重复      
    set.add(123);      
    set.add(true);        
    System.out.println("集合元素个数:"+set.size());        //遍历出集合中每一个元素       
    Iterator it=set.iterator();       
    while(it.hasNext()){         
        System.out.println(it.next());        
    }     
    }  
}
Copy after login

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();       //添加数据       
     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("元素个数:"+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();     
     }  
     }
Copy after login

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();       //添加数据       
    map.put("P01", "zhangSan");       
    map.put("P02", "Lucy");       
    map.put("PSex", "男");       
    map.put("PAge", "39");       
    map.put("PAge", "22");//key,重复会被后面的覆盖         //判断是否有一个key为PSex       
    if(map.containsKey("PSex")){        
        System.out.println("存在");        
    }      
    System.out.println("集合大小:"+map.size());      
    System.out.println("输出key为PAge的值:"+map.get("PAge"));        //遍历出Map集合中所有数据      
    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));    
    }      
    */    
    }  
    }
Copy after login

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

15 commonly used currency circle escape index technology analysis 15 commonly used currency circle escape index technology analysis Mar 03, 2025 pm 05:48 PM

In-depth analysis of the top 15 Bitcoin Escape Index: Market Outlook for 2025 This article deeply analyzes fifteen commonly used Bitcoin Escape Index, among which the Bitcoin Rhodl ratio, USDT current wealth management and altcoin seasonal index have reached the Escape Index in 2024, attracting market attention. How should investors deal with potential risks? Let us interpret these indicators one by one and explore reasonable response strategies. 1. Detailed explanation of key indicators AHR999 coin hoarding indicator: Created by ahr999, assisting Bitcoin fixed investment strategy. The current value is 1.21, which is in the wait-and-see range, so it is recommended to be cautious. Link to AHR999 Escape Top Indicator: A supplement to AHR999 Coin Hoarding Indicator, used to identify the top of the market. The current value is 2.48, this week

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles