Input/Output och strömmar i Java
Alex Liu
Software Development Engineer
HashSet för resten av videonimport java.util.HashSet;public class SampleHashSetData { public static void main(String[] args) { HashSet<String> fruits = new HashSet<>();fruits.add("Apple"); fruits.add("Banana");} }
{Apple, Banana}
For-Each-loopfor (type x: collection){}List, Set, Map med flerafruits: [Apple, Banana].for (String x : fruits) {
System.out.println(x);
}
Apple
Banana
Iterator<>: stöder List, Set, Queue med fleraIteratorimport java.util.Iterator;// Create `Iterator` object named `it` for sample set `fruits` Iterator<String> it = fruits.iterator(); // Use `.hasNext()` method checks if more elements exist while (it.hasNext()) { // User `.next()` retrieves the element System.out.print(it.next());}
Apple Banana
.remove() för att ta bort element med Iterator$$
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String fruit = it.next();
if (fruit.startsWith("A")) {
// Remove element if element startsWith `A`
it.remove();
}
}
// fruits now contains only "Banana"
Före borttagning:
System.out.println(fruits);
[Apple, Banana]
Efter borttagning:
System.out.println(fruits);
[Banana]
Garanterar säker borttagning och förhindrar ConcurrentModificationException

For-Each-loopList(ArrayList,LinkedList)Set(HashSet,TreeSet,LinkedHashSet)Queue(PriorityQueue)Stack(Stack)MapElement RemovalIteratorList(ArrayList,LinkedList)Set(HashSet,TreeSet,LinkedHashSet)Queue(PriorityQueue)Stack(Stack)Map (Kräver keySet().iterator, values().iterator eller entrySet().iterator)Element RemovalInput/Output och strömmar i Java