From b7f92e3ced6f4636b15198329be434198b129263 Mon Sep 17 00:00:00 2001 From: Hammy Date: Sun, 15 Nov 2020 04:07:31 +0000 Subject: [PATCH] Learning about Factory Methods and Collections Operations --- .../src/CollectionOperations.java | 22 +++++++++++++++ .../src/UnmodifiableVsImmutable.java | 28 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 Java Collections/src/CollectionOperations.java create mode 100644 Java Collections/src/UnmodifiableVsImmutable.java diff --git a/Java Collections/src/CollectionOperations.java b/Java Collections/src/CollectionOperations.java new file mode 100644 index 0000000..3cff38a --- /dev/null +++ b/Java Collections/src/CollectionOperations.java @@ -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(); + 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); + + } +} diff --git a/Java Collections/src/UnmodifiableVsImmutable.java b/Java Collections/src/UnmodifiableVsImmutable.java new file mode 100644 index 0000000..da92148 --- /dev/null +++ b/Java Collections/src/UnmodifiableVsImmutable.java @@ -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 mutableCountryToPopulation = new HashMap<>(); + mutableCountryToPopulation.put("UK", 67); + mutableCountryToPopulation.put("USA", 328); + + Map unmodifiableCountryToPopulation = Collections.unmodifiableMap(mutableCountryToPopulation); + Map 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); + + } +}