Learning about Factory Methods and Collections Operations

master
Hammy 4 years ago
parent b70d1476f8
commit b7f92e3ced

@ -0,0 +1,22 @@
import common.Product;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionOperations {
public static Product door = new Product("Wooden Door", 35);
public static Product floorPanel = new Product("Floor Panel", 25);
public static Product window = new Product("Glass Window", 10);
public static void main(String[] args) {
var products = new ArrayList<Product>();
Collections.addAll(products, door, floorPanel, window);
System.out.println(Collections.max(products, Product.BY_WEIGHT));
System.out.println(Collections.min(products, Product.BY_WEIGHT));
Collections.fill(products, null);
System.out.println("products = " + products);
}
}

@ -0,0 +1,28 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class UnmodifiableVsImmutable {
public static void main(String[] args) {
Map<String, Integer> mutableCountryToPopulation = new HashMap<>();
mutableCountryToPopulation.put("UK", 67);
mutableCountryToPopulation.put("USA", 328);
Map<String, Integer> unmodifiableCountryToPopulation = Collections.unmodifiableMap(mutableCountryToPopulation);
Map<String, Integer> copiedCountryToPopulation = Map.copyOf(mutableCountryToPopulation);
// Throws UnsupportedOperationException: unmodifiableCountryToPopulation.put("Germany", 83);
// Throws UnsupportedOperationException: copiedCountryToPopulation.put("Germany", 83);
System.out.println("copiedCountryToPopulation = " + copiedCountryToPopulation);
System.out.println("unmodifiableCountryToPopulation = " + unmodifiableCountryToPopulation);
mutableCountryToPopulation.put("Germany", 83);
System.out.println("copiedCountryToPopulation = " + copiedCountryToPopulation);
System.out.println("unmodifiableCountryToPopulation = " + unmodifiableCountryToPopulation);
// Short way of constructing a Map
var countryToPopulation = Map.of("UK", 67, "USA", 328);
// Throws UnsupportedOperationException: countryToPopulation.put("Germany", 83);
}
}
Loading…
Cancel
Save