1. 程式人生 > >Set集合基本操作方法

Set集合基本操作方法

test sem 增加 emp 判斷 system port 基本操作 全部

package com.wy.test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetTest {
    public static void main(String[] args) {
        Set<String> set = new HashSet();

        //1.增加元素
        set.add("001");
        set.add("002");
        set.add("003");
        set.add(
"004"); set.add("005"); System.out.println(set); System.out.println("----------------------"); //元素數量 int num = set.size(); System.out.println(num); System.out.println("----------------------"); //元素刪除 set.remove("002"); System.out.println(set); System.out.println(
"----------------------"); //使用叠代器遍歷 Iterator it = set.iterator(); while (it.hasNext()){ Object item = it.next(); String s = (String)item;//強制轉換 System.out.println(s); } System.out.println("----------------------"); //元素全部刪除
set.clear(); System.out.println(set); System.out.println("----------------------"); //判斷集合是否為空 boolean b = set.isEmpty(); System.out.println(b); } }

輸出結果

[001, 002, 003, 004, 005]
----------------------
5
----------------------
[001, 003, 004, 005]
----------------------
001
003
004
005
----------------------
[]
----------------------
true

Set集合基本操作方法