Lesson 5

Generics, Lists, Maps

This lesson is describing creating and using classes which allows to pass a type as a parameter. In fact, maps are not a data structure, but for this lesson we will assume that they are.

I. Creating a class with a generic type

Task 0

Consider a class that contains String or Integer object.

class StringWrapper {
  String value;
class IntegerWrapper {
  Integer value;

Those classes are very similar, so we would like to create something more universal by using a diamond:

class Wrapper<T> {
  T value;
Wrapper<String> stringWrapper;
Wrapper<Integer> integerWrapper;

Create a class which contains an array of a specific type. Its size will be passed as the argument in a constructor.

II. Listy i mapy

Array List Map
The fastest Slower (depends on implementation)
You have to provide a size Size is optional
Size is fixed Size is changing dynamic
Index of an object is an integer Index is of any type
No support for a diamond One parameter type required Two parameter types required (index, value)
Introduction to basic structures - collections Introduction to basic structures - collections
Kod do obsługi list
// Creating a list of a specific type
List<Integer> list = new ArrayList<>();

// Adding an element to the list

// Getting an element from the list (index as an argument)

// Cheking if the list contains an element given as an argument

// Overriding the element with an index 0 with a new value 10
list.set(0, 10);

// Deleting an element with an index 0

// Deleting all elements from the list
Map sample code
// Creating a mapping from String to String
Map<String, String> map = new HashMap<>();

// Putting a value “Warsaw” for a key “Poland”
map.put("Polska", "Warszawa");

// Getting a value for a key "Poland"

// Checking if a key “Japan” exists

// Getting a set of all keys

// Deleting a key (so its value)

// Deleting all keys (and values)
Task 1

Create Rectangle class (x, y, width, height, color).

Next create a class which contains a list of rectangles. This class will start a thread which will add to the list pseudorandom generated rectangle each 10 seconds. You can call it e.g. RectangleContainer.

Create a window class that contains a rectangle container. The window purpose is to draw all the rectangles.

Task 2

Create QuotationFrame class.

A purpose of this class is to show quotations in a window.
Text can be loaded from a file.
A quoted person can have many quotations,
so text should be shown similar to the example found below.

Screen listing quotations of famous writers
Screen listing quotations of famous writers

III. Nesting structures

Nesting structures Nesting structures
Nesting structures (color version) Nesting structures (color version)