Recap - Generic Container
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 58 of 87.
Challenge
EasyLet's build a versatile storage system that brings together everything you've learned about generics! You'll create a Container class that can store, retrieve, and process elements of any type, along with utility methods that demonstrate wildcards in action.
You'll organize your code across three files:
Container.java: Create a generic classContainer<T>that manages a collection of items. Your container should use anArrayList<T>internally to store elements. Include methods toadd(T item)an element,get(int index)to retrieve an element at a specific position,size()to return the count of items, andisEmpty()to check if the container has no elements. Also add agetAll()method that returns the internal list.ContainerUtils.java: Create a utility class with static generic methods that work with your containers:printAll(Container<?> container)- Uses an unbounded wildcard to print all elements in any container, one per line.countItems(Container<? extends Number> container)- Uses an upper bounded wildcard to calculate the sum of all numeric values in the container, returning the result as adouble.addDefaults(Container<? super Integer> container)- Uses a lower bounded wildcard to add the integers 1, 2, and 3 to any container that can hold integers.<T> T getLastOrDefault(Container<T> container, T defaultValue)- A generic method that returns the last element in the container, or the default value if the container is empty.Main.java: Bring your generic container system together! You'll receive three inputs: a word (String), an integer, and a double.First, create a
Container<String>and add the word to it twice. PrintString container:then useprintAllto display its contents.Next, create a
Container<Double>and add the double value to it. Print a blank line, thenNumber sum: [sum]usingcountItems.Then create a
Container<Number>and calladdDefaultson it. Print a blank line, thenAfter adding defaults:and useprintAllto show the contents.Finally, create an empty
Container<Integer>and usegetLastOrDefaultwith your integer input as the default. Print a blank line, thenLast or default: [result].
You will receive three inputs in order: a word (String), an integer, and a double.
This challenge combines generic classes, generic methods, bounded type parameters, and all three wildcard types. Notice how each piece serves a different purpose: the generic class provides type-safe storage, bounded wildcards enable flexible reading and writing, and generic methods offer reusable operations across different container types!
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String word = scanner.nextLine();
int intValue = Integer.parseInt(scanner.nextLine());
double doubleValue = Double.parseDouble(scanner.nextLine());
// TODO: Create a Container<String> and add the word twice
// Print "String container:" then use ContainerUtils.printAll()
// TODO: Create a Container<Double> and add the double value
// Print a blank line, then "Number sum: [sum]" using ContainerUtils.countItems()
// TODO: Create a Container<Number> and call ContainerUtils.addDefaults() on it
// Print a blank line, then "After adding defaults:" and use ContainerUtils.printAll()
// TODO: Create an empty Container<Integer>
// Use ContainerUtils.getLastOrDefault() with intValue as default
// Print a blank line, then "Last or default: [result]"
}
}
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System9Generics
Introduction to GenericsGeneric ClassesGeneric MethodsBounded Type ParametersWildcards (?, extends, super)Recap - Generic Container