溫馨提示×

java如何獲取map中元素個數(shù)

小億
128
2024-06-06 18:37:18
欄目: 編程語言

在Java中,可以使用Map接口的size()方法來獲取Map中元素的個數(shù)。示例如下:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);
        
        int size = map.size();
        
        System.out.println("Map中元素的個數(shù)為: " + size);
    }
}

在上面的示例中,首先創(chuàng)建了一個HashMap對象,并向其中放入了三個鍵值對。然后通過調(diào)用size()方法獲取Map中元素的個數(shù),并將結果打印出來。

0