Unique objects

Report a typo

This simple program simulates a text editor that supports different typefaces and sizes of characters. Each character in the Editor class is represented by a Glyph object which stores the character itself, as well as its font and size. As glyphs may repeat in a long text, it's a good idea to cache them in order to avoid creating unnecessary objects.

Your task is to write the getOrPut method in the GlyphCache class that accepts a character, its font and size, and then returns the corresponding Glyph which is either retrieved from cache or created on demand. The main purpose of this method is to make sure that only one Glyph object is created with any unique combination of the character, font and size.

Consider calculating a hash to solve this task.

Write a program in Java 17
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;

class Editor {
private String font;
private int size;
private final List<Glyph> glyphs = new ArrayList<>();
private final GlyphCache cache = new GlyphCache();

public void appendChar(char ch) {
Glyph glyph = cache.getOrPut(ch, font, size);
glyphs.add(glyph);
}

public List<Glyph> getGlyphs() {
return glyphs;
}

public void setFont(String font) {
this.font = font;
}

public void setSize(int size) {
this.size = size;
}
}

class GlyphCache {
// write your code here

___

Create a free account to access the full topic