I need to create a multiset on Java

672 Views Asked by At

I have to create a MultiSet in Java and I'm stuck. I need to have it efficient and without superfluous pointers, one pointer and the value, using the Java Collections. The problem is that I have to use Set<Element<E>> that is not a clean solution, also I didn't know how use an iterator with this solution. A first solution was using a class Element<E> that stores an "item" and a key.

private Set<Element<E>> elements;
private int size;
private int numeroModifiche;


private static class Element<E> {
    // la classe element si riferisce ad un'elemento del multiset, essa contiene oltre all'oggetto(non modificabile)
    // anche le volte in cui è presente che possono solo incrementare o decrementare di 1
    private final E item;
    private int frequency;

    //viene inizializata con l'item fornito e la frequenta fornita
    public Element(E item, int frequency) {
        if (item == null)
            throw new NullPointerException("item non può essere nullo");
        if (frequency < 0)
            throw new IllegalArgumentException("La frequenza non può essere negativa");
        this.item = item;
        this.frequency = frequency;
    }

    // aggiungiamo unità
    public boolean addFrequency(int f) {
        // se siamo arrivati al numero massimo di elementi inseribili non possiamo più aggiungere nulla
        if (frequency + f >= Integer.MAX_VALUE)
            throw new IllegalArgumentException("La frequenza supererebbe il limite consentito ");

        // altrimenti aggiungiamo f
        this.frequency += f;
        return true;

    }

    public boolean removeFrequency(int f) {
        // se la differenza porta un numero inferiore allo 0 gli assegniamo 0
        frequency = Math.max(0, frequency - f);
        return frequency != 0;
    }

    // creiamo il metodo hashcode che si occupa solo dell'item cosi da far funzionare i vari contains
    public int hashCode() {
        return item.hashCode();
    }

    public boolean equals(Object e) {
        if (e == null)
            return false;
        if (!(e instanceof Element))
            return false;
        return item.equals(((Element) e).getItem());
    }

    // otteniamo il valore
    public E getItem() {
        return item;
    }

    // otteniamo il numero di elementi presenti
    public int getFrequency() {
        return frequency;
    }

}

this is the actual code

0

There are 0 best solutions below