Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
1.8 kB
2
Indexable
Never
package com.company;

import java.util.Iterator;
import java.util.Stack;

public class Lista implements Iterable<Osoba> {
    Osoba[] lista;
    int length;
    int n = 0;

    public Lista(int n) {
        this.lista = new Osoba[n];
        this.length = lista.length;
    }

    public void add(Osoba o) {
        if (n == lista.length) {
            Osoba[] nl = new Osoba[2 * lista.length];
            System.arraycopy(lista, 0, nl, 0, n);
            lista = nl;
        }

        lista[n] = o;
        n++;
    }

    public int getSize() {
        return n;
    }

    public void usun(Osoba o) { // ni chuja nie wiem jak to usuwać
        while (iterator().hasNext()) {
            Iterator<Osoba> it = iterator();
            Osoba ow = it.next();
            if (ow.equals(o)) {
                ow = null;
                n--;
            }
        }
    }

    @Override
    public Iterator<Osoba> iterator() {
        return new Iterator<Osoba>() {
            Osoba[] t = new Osoba[length];
            int curr = 0;

            {
                System.arraycopy(lista, 0, t, 0, n);
            }

            @Override
            public boolean hasNext() {
                return curr < n;
            }

            @Override
            public Osoba next() {
                return t[curr++];
            }

        };
    }

    @Override
    public String toString() {
        Iterator<Osoba> itr = iterator();
        StringBuilder sb = new StringBuilder();
        while (itr.hasNext()) {
            //System.out.println(itr.next());
            //jakoś dodaj do string(array???)
            sb.append(itr.next().toString());
            sb.append(" ");
        }
        return sb.toString();
    }

}