0

我必须在 Java 中创建一个 MultiSet 并且我被卡住了。我需要使用 Java 集合使其高效且没有多余的指针、一个指针和值。问题是我必须使用Set<Element<E>>这不是一个干净的解决方案,我也不知道如何在这个解决方案中使用迭代器。第一个解决方案是使用一个Element<E>存储“项目”和密钥的类。

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;
    }

}

这是实际的代码

4

0 回答 0