Co do nie pozwolić na tworzenie - to nie ma sensu - pozwól na tworzenie. (new).
To co chcesz zrobić (tylko o tym nie wiesz) - to np. trzymaj wszystkich Uczn w kolekcji HashSet<Uczen>. I sprawdzaj przed dodaniem do kolekcji czy on tam jest: (contains(nowoDodanyUczen), kóre zreszstą w środku wywoła equals) i jak się okaże że już jest taki uczeń -to daj uzytownikowi komunikat: *Jest już taki uczeń i nie wolno go dodać drugi raz. Ty niedobry.,,, *
equals i hashCode takie jakie chcesz możesz sobie wygenerować przez IDE
mi wyszło takie:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Uczen uczen = (Uczen) o;
if (imie != null ? !imie.equals(uczen.imie) : uczen.imie != null) return false;
return nazwisko != null ? nazwisko.equals(uczen.nazwisko) : uczen.nazwisko == null;
}
@Override
public int hashCode() {
int result = imie != null ? imie.hashCode() : 0;
result = 31 * result + (nazwisko != null ? nazwisko.hashCode() : 0);
return result;
}
ale alternatywa
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Uczen uczen = (Uczen) o;
if (imie != null ? !imie.equals(uczen.imie) : uczen.imie != null) return false;
return nazwisko != null ? nazwisko.equals(uczen.nazwisko) : uczen.nazwisko == null;
}
@Override
public int hashCode() {
return 1;
}
też będzie działać - spełnia warunki - po prostu nie będzie super efektywna :-)
ale jak masz tych uczniów do 30 to jest całkiem ok.