Java程序移除Set集合中的所有元素


假设我们有一个包含多个元素的Set,我们的任务是编写一个Java程序来移除Set中的元素。这里,Set是Java集合接口的一个子接口,它定义了一个数学集合。

在Java中移除Set元素

要移除Java中给定Set中的元素,可以使用以下方法:

  • 使用clear()方法
  • 使用removeAll()方法
  • 使用迭代器和remove()

使用Java clear()方法

借助clear()方法,我们可以移除给定Set中的所有元素。此方法不接收任何参数,也不返回值。它只清空现有的Set。

示例

以下是使用clear()方法移除给定Set中所有元素的示例。

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet  set1 = new HashSet ();
      set1.add("Mat");
      set1.add("Sat");
      set1.add("Cat");
      System.out.println("Set = "+ set1);
      set1.clear();
      System.out.println("Set after removing all the elements (blank) = "+ set1);
    }
}

上述代码的输出如下:

Set = [Mat, Sat, Cat]
Set after removing all the elements (blank) = []

使用removeAll()方法

removeAll()方法接收一个Set作为参数并移除其元素。如果元素成功移除,则返回TRUE,否则返回FALSE

示例

在这个示例中,我们使用removeAll()方法移除指定Set中的所有元素。

import java.util.*;
public class Main {
   public static void main(String args[]) {
      HashSet <String> set1 = new HashSet <String>();
      set1.add("Put");
      set1.add("Cut");
      set1.add("Tutor");
      set1.add("Tutorix");
      System.out.println("Set = " + set1);
      set1.removeAll(set1);
      System.out.println("Set after removing all the elements (blank) = "+ set1);
   }
}

执行上述代码后,会产生以下结果:

Set = [Tutor, Cut, Tutorix, Put]
Set after removing all the elements (blank) = []

使用迭代器和remove()

我们将使用迭代器遍历Set的每个元素,并使用remove()方法逐个移除元素。

示例

以下示例演示了如何使用迭代器和remove()移除给定Set对象中的元素。

import java.util.*;
public class Main {
   public static void main(String args[]) {
      HashSet <String> set1 = new HashSet <String>();
      set1.add("Tutorials");
      set1.add("Articles");
      set1.add("Tutor");
      set1.add("Tutorix");
      set1.add("Courses");
      System.out.println("Set = " + set1);
      Iterator<String> iter = set1.iterator();
      while (iter.hasNext()) {
         iter.next();
         iter.remove(); 
      }
      System.out.println("Set after removing all the elements (blank) = "+ set1);
   }
}

运行上述代码后,将显示以下输出:

Set = [Tutor, Articles, Tutorials, Courses, Tutorix]
Set after removing all the elements (blank) = []

更新时间: 2024年8月1日

1K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.