Java集合(Collection)是一个框架,它提供了操作一组对象的方法。集合的长度或大小,通常通过调用集合类的 size() 方法来获取。不同的集合类(如 ArrayListHashSetLinkedList 等)都继承自 Collection 接口或它的子接口(如 ListSet),它们都有 size() 方法。

示例1:

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set; 
public class CollectionSizeExample {
    public static void main(String[] args) {
        // 创建ArrayList
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        arrayList.add("Cherry");
 
        // 获取ArrayList的长度
        System.out.println("ArrayList size: " + arrayList.size());
 
        // 创建HashSet
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Dog");
        hashSet.add("Cat");
        hashSet.add("Bird");
 
        // 获取HashSet的长度
        System.out.println("HashSet size: " + hashSet.size());
 
        // 创建LinkedList
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
 
        // 获取LinkedList的长度
        System.out.println("LinkedList size: " + linkedList.size());
    }
}

示例2,Collections类方法:

import java.util.*; 
public class Main {
   public static void main(String [] args) {   
      System.out.println( "集合实例!\n" ); 
      int size;
      HashSet collection = new HashSet ();
      String str1 = "Yellow", str2 = "White", str3 = 
      "Green", str4 = "Blue";  
      Iterator iterator;
      collection.add(str1);    
      collection.add(str2);   
      collection.add(str3);   
      collection.add(str4);
      System.out.print("集合数据: ");  


      iterator = collection.iterator();     
      while (iterator.hasNext()){
         System.out.print(iterator.next() + " ");  
      }
      System.out.println();
      size = collection.size();
      if (collection.isEmpty()){
         System.out.println("集合是空的");
      }
      else{
         System.out.println( "集合长度: " + size);
      }
      System.out.println();
   }
}

 

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐