Jonalca
Jonalca

Reputation: 576

TreeMap as a generic class

I want to learn TreeMap from Java Collections and make an example code with generics.

I had the idea of making "an ordered list" of whatever type you want it to be, (e.g) where Employees are ordered alphabetical by name and Integer are their IDs or where Students are ordered by their ID and Student is a custom Object.

I want some help or guidance to learn this Java Collection and solve this problem.

My generic class

public class GenericTreeMap<E1, E2> extends TreeMap<E1, E2>{
    private E1 e1;
    private E2 e2;

    public GenericTreeMap(E1 e1, E2 e2) {
        this.e1 = e1;
        this.e2 = e2;
    }

    public void printTypes() {
        System.out.println("Key type: " + e1.getClass().getName());
        System.out.println("Value type: " + e2.getClass().getName());
    }
}

Main

Empleado e = new Empleado();
GenericTreeMap<Empleado, Integer> treeMap = new GenericTreeMap<>(e, "");
treeMap.put(new Empleado(1, 1500), "Ricardo");
treeMap.put(new Empleado(2, 1200), "Gerardo");
treeMap.put(new Empleado(3, 300), "Becario");
treeMap.put(new Empleado(4, 0), "Esclavo");

treeMap.values();

Expected Output

Key type: Employee

Value type: Integer

Edit: My code does not work as intended.

Upvotes: 0

Views: 482

Answers (1)

mentallurg
mentallurg

Reputation: 5207

Use List, not Map. Implement Comparable in your element class, or implement a Comparator, or use Comparator in combination with streams. Map is a wrong tool to implement what you need.

There is of course a possibility to keep elements ordered in the TreeMap. Depending on what order you need you can implement a Comparator and provide it when you create a TreeMap. But handling it may be more complex than using a List.

Upvotes: 1

Related Questions