Примеры Java - Удаление указанного элемента из коллекции

Java 实例Примеры Java

В следующем примере показано, как использовать метод collection.remove() класса Collection для удаления указанного элемента из коллекции:

Файл Main.java

import java.util.*; public class Main { public static void main(String [] args) { System.out.println( "Пример коллекции!\n" ); int size; HashSet collection = new HashSet (); String str1 = "Желтый", str2 = "Белый", str3 = "Зеленый", str4 = "Синий"; 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(); collection.remove(str2); System.out.println("После удаления [" + str2 + "]\n"); System.out.print("Теперь данные коллекции:"); iterator = collection.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } System.out.println(); size = collection.size(); System.out.println("Размер коллекции:" + size + "\n"); } }

Вывод выполнения приведенного выше кода:

集合实例!

集合数据: White Yellow Blue Green 
删除之后 [White]

现在集合的数据是: Yellow Blue Green 
集合大小: 3

Java 实例Примеры Java

Другие расширения