Commit 9f840176 by Patryk Czarnik

Koniec wątków i ostatnie przykłady

parent 152c09ae
package p19_porownywanie.v1_brak_equals;
public class HaszKody {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// Jeśli w klasie nie nadpiszemy metody hashCode, to działa domyślna implementacja
// wyliczająca hashcode na podstawie adresu.
// Daje to efekt, że haszkody różnych obiektów są różne.
// Dopóki nie tworzymy miliardów obiektów, to hashcody będą unikalne.
System.out.println("hasz a " + a.hashCode());
System.out.println("hasz r " + r.hashCode());
System.out.println("hasz b " + b.hashCode());
System.out.println("hasz c " + c.hashCode());
}
}
package p19_porownywanie.v1_brak_equals;
public class Osoba {
String imie, nazwisko;
int wiek;
public Osoba(String imie, String nazwisko, int wiek) {
this.imie = imie;
this.nazwisko = nazwisko;
this.wiek = wiek;
}
@Override
public String toString() {
return "Osoba [imie=" + imie + ", nazwisko=" + nazwisko + ", wiek=" + wiek + "]";
}
}
package p19_porownywanie.v1_brak_equals;
import java.util.Objects;
public class Porownywanie {
// Jeśli w klasie nie zdefiniujemy metody equals, to używana jest domyślna implementacja pochodząca z klasy Object,
// która porównuje adresy (działa jak ==).
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// == sprawdza cz yto jest ten sam adres
System.out.println("a == a " + (a == a));
System.out.println("a == r " + (a == r));
System.out.println("a == b " + (a == b));
System.out.println("a == c " + (a == c));
System.out.println();
System.out.println("a.equals(a) " + (a.equals(a)));
System.out.println("a.equals(r) " + (a.equals(r)));
System.out.println("a.equals(b) " + (a.equals(b)));
System.out.println("a.equals(c) " + (a.equals(c)));
System.out.println();
System.out.println("Obj a a " + Objects.equals(a, a));
System.out.println("Obj a r " + Objects.equals(a, r));
System.out.println("Obj a b " + Objects.equals(a, b));
System.out.println("Obj a c " + Objects.equals(a, c));
System.out.println();
}
}
package p19_porownywanie.v1_brak_equals;
import java.util.Set;
import java.util.TreeSet;
public class ZbiorDrzewowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// TreeSet oraz TreeMap w działaniu korzystają z metody compareTo (ewentualnie z komparatora).
// Ten program kończy sie błedem, bo Osoba nie jest Comparable
boolean wynik;
Set<Osoba> zbior = new TreeSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v1_brak_equals;
import java.util.HashSet;
import java.util.Set;
public class ZbiorHaszowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// HashSet oraz HashMap w działaniu korzystają z metod hashCode i equals.
// 1) patrzy jaki jest hashcode i jeśli różny, to traktuje jak różne obiekty
// 2) jeśli hc jest równy, to wtedy porówuje za pomocą equals
boolean wynik; // wynik operacji add: jeśli element został dodany to true, a jeśli nie to false
Set<Osoba> zbior = new HashSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilość elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v2_bledny_equals;
public class HaszKody {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// Jeśli w klasie nie nadpiszemy metody hashCode, to działa domyślna implementacja
// wyliczająca hashcode na podstawie adresu.
// Daje to efekt, że haszkody różnych obiektów są różne.
// Dopóki nie tworzymy miliardów obiektów, to hashcody będą unikalne.
System.out.println("hasz a " + a.hashCode());
System.out.println("hasz r " + r.hashCode());
System.out.println("hasz b " + b.hashCode());
System.out.println("hasz c " + c.hashCode());
}
}
package p19_porownywanie.v2_bledny_equals;
import java.util.Objects;
public class Osoba {
String imie, nazwisko;
int wiek;
public Osoba(String imie, String nazwisko, int wiek) {
this.imie = imie;
this.nazwisko = nazwisko;
this.wiek = wiek;
}
@Override
public String toString() {
return "Osoba [imie=" + imie + ", nazwisko=" + nazwisko + ", wiek=" + wiek + "]";
}
// To nie jest "overriding" tylko "overloading".
// Nie nadpisuję "prawdziwej" metody equals pochodzącej z Object, tylko towrzę nową dodatkową metodę odstepną tylko w klasie Osoba.
// Ten equals zadziała tylko jeśli bezpośrednio go wywołamy na obiekcie Osoba,
// ale to nie jest "ten prawdziwy" equals, i Java (np. HashSet) nie będzie brać tej definicji pod uwagę.
public boolean equals(Osoba inna) {
return inna != null
&& Objects.equals(this.imie, inna.imie)
&& Objects.equals(this.nazwisko, inna.nazwisko)
&& this.wiek == inna.wiek;
}
public int hashCode() {
// to jest niewydajne, ale poprawne i muszę to dopisać, aby "oszukać" hashset
return 0;
}
}
package p19_porownywanie.v2_bledny_equals;
import java.util.Objects;
public class Porownywanie {
// Jeśli w klasie nie zdefiniujemy metody equals, to używana jest domyślna implementacja pochodząca z klasy Object,
// która porównuje adresy (działa jak ==).
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// == sprawdza cz yto jest ten sam adres
System.out.println("a == a " + (a == a));
System.out.println("a == r " + (a == r));
System.out.println("a == b " + (a == b));
System.out.println("a == c " + (a == c));
System.out.println();
System.out.println("a.equals(a) " + (a.equals(a)));
System.out.println("a.equals(r) " + (a.equals(r)));
System.out.println("a.equals(b) " + (a.equals(b)));
System.out.println("a.equals(c) " + (a.equals(c)));
System.out.println();
System.out.println("Obj a a " + Objects.equals(a, a));
System.out.println("Obj a r " + Objects.equals(a, r));
System.out.println("Obj a b " + Objects.equals(a, b));
System.out.println("Obj a c " + Objects.equals(a, c));
System.out.println();
}
}
package p19_porownywanie.v2_bledny_equals;
import java.util.Set;
import java.util.TreeSet;
public class ZbiorDrzewowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// TreeSet oraz TreeMap w działaniu korzystają z metody compareTo (ewentualnie z komparatora).
// Ten program kończy sie błedem, bo Osoba nie jest Comparable
boolean wynik;
Set<Osoba> zbior = new TreeSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v2_bledny_equals;
import java.util.HashSet;
import java.util.Set;
public class ZbiorHaszowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// HashSet oraz HashMap w działaniu korzystają z metod hashCode i equals.
boolean wynik; // wynik operacji add: jeśli element został dodany to true, a jeśli nie to false
Set<Osoba> zbior = new HashSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v3_equals;
public class HaszKody {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// Jeśli w klasie nie nadpiszemy metody hashCode, to działa domyślna implementacja
// wyliczająca hashcode na podstawie adresu.
// Daje to efekt, że haszkody różnych obiektów są różne.
// Dopóki nie tworzymy miliardów obiektów, to hashcody będą unikalne.
System.out.println("hasz a " + a.hashCode());
System.out.println("hasz r " + r.hashCode());
System.out.println("hasz b " + b.hashCode());
System.out.println("hasz c " + c.hashCode());
}
}
package p19_porownywanie.v3_equals;
import java.util.Objects;
public class Osoba {
String imie, nazwisko;
int wiek;
public Osoba(String imie, String nazwisko, int wiek) {
this.imie = imie;
this.nazwisko = nazwisko;
this.wiek = wiek;
}
public String toString() {
return "Osoba [imie=" + imie + ", nazwisko=" + nazwisko + ", wiek=" + wiek + "]";
}
public boolean equals(Object obj) {
if(obj == null || ! (obj instanceof Osoba)) {
return false;
}
Osoba inna = (Osoba)obj;
return Objects.equals(this.imie, inna.imie)
&& Objects.equals(this.nazwisko, inna.nazwisko)
&& this.wiek == inna.wiek;
}
// Formalnym wymaganiem wobec hashCode jest:
// jeśli dwa obiekty są równe (equals), to hashcode'y muszą być równe
// Natomiast dla zwiększenia wydajności jeśli obiekty są różne,
// to z dużym pradopodobieństwem hashcody powinny być różne.
public int hashCode() {
return 0;
}
}
package p19_porownywanie.v3_equals;
import java.util.Objects;
public class Porownywanie {
// Jeśli w klasie nie zdefiniujemy metody equals, to używana jest domyślna implementacja pochodząca z klasy Object,
// która porównuje adresy (działa jak ==).
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// == sprawdza cz yto jest ten sam adres
System.out.println("a == a " + (a == a));
System.out.println("a == r " + (a == r));
System.out.println("a == b " + (a == b));
System.out.println("a == c " + (a == c));
System.out.println();
System.out.println("a.equals(a) " + (a.equals(a)));
System.out.println("a.equals(r) " + (a.equals(r)));
System.out.println("a.equals(b) " + (a.equals(b)));
System.out.println("a.equals(c) " + (a.equals(c)));
System.out.println();
System.out.println("Obj a a " + Objects.equals(a, a));
System.out.println("Obj a r " + Objects.equals(a, r));
System.out.println("Obj a b " + Objects.equals(a, b));
System.out.println("Obj a c " + Objects.equals(a, c));
System.out.println();
}
}
package p19_porownywanie.v3_equals;
import java.util.Set;
import java.util.TreeSet;
public class ZbiorDrzewowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// TreeSet oraz TreeMap w działaniu korzystają z metody compareTo (ewentualnie z komparatora).
// Ten program kończy sie błędem, bo Osoba nie jest Comparable.
boolean wynik;
Set<Osoba> zbior = new TreeSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v3_equals;
import java.util.HashSet;
import java.util.Set;
public class ZbiorHaszowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// HashSet oraz HashMap w działaniu korzystają z metod hashCode i equals.
boolean wynik; // wynik operacji add: jeśli element został dodany to true, a jeśli nie to false
Set<Osoba> zbior = new HashSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v4_equals_generowany;
public class HaszKody {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// Jeśli w klasie nie nadpiszemy metody hashCode, to działa domyślna implementacja
// wyliczająca hashcode na podstawie adresu.
// Daje to efekt, że haszkody różnych obiektów są różne.
// Dopóki nie tworzymy miliardów obiektów, to hashcody będą unikalne.
System.out.println("hasz a " + a.hashCode());
System.out.println("hasz r " + r.hashCode());
System.out.println("hasz b " + b.hashCode());
System.out.println("hasz c " + c.hashCode());
}
}
package p19_porownywanie.v4_equals_generowany;
public class Osoba {
String imie, nazwisko;
int wiek;
public Osoba(String imie, String nazwisko, int wiek) {
this.imie = imie;
this.nazwisko = nazwisko;
this.wiek = wiek;
}
@Override
public String toString() {
return "Osoba [imie=" + imie + ", nazwisko=" + nazwisko + ", wiek=" + wiek + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((imie == null) ? 0 : imie.hashCode());
result = prime * result + ((nazwisko == null) ? 0 : nazwisko.hashCode());
result = prime * result + wiek;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
// lepiej tak sprawdzać klasę niż za pomocą instanceof
if (getClass() != obj.getClass())
return false;
Osoba other = (Osoba) obj;
if (imie == null) {
if (other.imie != null)
return false;
} else if (!imie.equals(other.imie))
return false;
if (nazwisko == null) {
if (other.nazwisko != null)
return false;
} else if (!nazwisko.equals(other.nazwisko))
return false;
if (wiek != other.wiek)
return false;
return true;
}
}
package p19_porownywanie.v4_equals_generowany;
import java.util.Objects;
public class Porownywanie {
// Jeśli w klasie nie zdefiniujemy metody equals, to używana jest domyślna implementacja pochodząca z klasy Object,
// która porównuje adresy (działa jak ==).
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// == sprawdza cz yto jest ten sam adres
System.out.println("a == a " + (a == a));
System.out.println("a == r " + (a == r));
System.out.println("a == b " + (a == b));
System.out.println("a == c " + (a == c));
System.out.println();
System.out.println("a.equals(a) " + (a.equals(a)));
System.out.println("a.equals(r) " + (a.equals(r)));
System.out.println("a.equals(b) " + (a.equals(b)));
System.out.println("a.equals(c) " + (a.equals(c)));
System.out.println();
System.out.println("Obj a a " + Objects.equals(a, a));
System.out.println("Obj a r " + Objects.equals(a, r));
System.out.println("Obj a b " + Objects.equals(a, b));
System.out.println("Obj a c " + Objects.equals(a, c));
System.out.println();
}
}
package p19_porownywanie.v4_equals_generowany;
import java.util.Set;
import java.util.TreeSet;
public class ZbiorDrzewowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// TreeSet oraz TreeMap w działaniu korzystają z metody compareTo (ewentualnie z komparatora).
// Ten program kończy sie błedem, bo Osoba nie jest Comparable
boolean wynik;
Set<Osoba> zbior = new TreeSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v4_equals_generowany;
import java.util.HashSet;
import java.util.Set;
public class ZbiorHaszowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// HashSet oraz HashMap w działaniu korzystają z metod hashCode i equals.
boolean wynik; // wynik operacji add: jeśli element został dodany to true, a jeśli nie to false
Set<Osoba> zbior = new HashSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v5_equals_oraz_comparable;
public class HaszKody {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// Jeśli w klasie nie nadpiszemy metody hashCode, to działa domyślna implementacja
// wyliczająca hashcode na podstawie adresu.
// Daje to efekt, że haszkody różnych obiektów są różne.
// Dopóki nie tworzymy miliardów obiektów, to hashcody będą unikalne.
System.out.println("hasz a " + a.hashCode());
System.out.println("hasz r " + r.hashCode());
System.out.println("hasz b " + b.hashCode());
System.out.println("hasz c " + c.hashCode());
}
}
package p19_porownywanie.v5_equals_oraz_comparable;
import java.util.Comparator;
import java.util.Objects;
public class Osoba implements Comparable<Osoba> {
String imie, nazwisko;
int wiek;
public Osoba(String imie, String nazwisko, int wiek) {
this.imie = imie;
this.nazwisko = nazwisko;
this.wiek = wiek;
}
public String getImie() {
return imie;
}
public String getNazwisko() {
return nazwisko;
}
public int getWiek() {
return wiek;
}
@Override
public String toString() {
return "Osoba [imie=" + imie + ", nazwisko=" + nazwisko + ", wiek=" + wiek + "]";
}
@Override
public int hashCode() {
return Objects.hash(imie, nazwisko, wiek);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Osoba other = (Osoba) obj;
return Objects.equals(imie, other.imie) && Objects.equals(nazwisko, other.nazwisko) && wiek == other.wiek;
}
@Override
public int compareTo(Osoba inna) {
return komparator.compare(this, inna);
}
private final static Comparator<Osoba> komparator =
Comparator.comparing(Osoba::getNazwisko)
.thenComparing(Osoba::getImie)
.thenComparing(Osoba::getWiek);
}
package p19_porownywanie.v5_equals_oraz_comparable;
import java.util.Objects;
public class Porownywanie {
// Jeśli w klasie nie zdefiniujemy metody equals, to używana jest domyślna implementacja pochodząca z klasy Object,
// która porównuje adresy (działa jak ==).
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// == sprawdza cz yto jest ten sam adres
System.out.println("a == a " + (a == a));
System.out.println("a == r " + (a == r));
System.out.println("a == b " + (a == b));
System.out.println("a == c " + (a == c));
System.out.println();
System.out.println("a.equals(a) " + (a.equals(a)));
System.out.println("a.equals(r) " + (a.equals(r)));
System.out.println("a.equals(b) " + (a.equals(b)));
System.out.println("a.equals(c) " + (a.equals(c)));
System.out.println();
System.out.println("Obj a a " + Objects.equals(a, a));
System.out.println("Obj a r " + Objects.equals(a, r));
System.out.println("Obj a b " + Objects.equals(a, b));
System.out.println("Obj a c " + Objects.equals(a, c));
System.out.println();
}
}
package p19_porownywanie.v5_equals_oraz_comparable;
import java.util.Set;
import java.util.TreeSet;
public class ZbiorDrzewowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// TreeSet oraz TreeMap w działaniu korzystają z metody compareTo (ewentualnie z komparatora).
// Ten program kończy sie błedem, bo Osoba nie jest Comparable
boolean wynik;
Set<Osoba> zbior = new TreeSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p19_porownywanie.v5_equals_oraz_comparable;
import java.util.HashSet;
import java.util.Set;
public class ZbiorHaszowy {
public static void main(String[] args) {
Osoba a = new Osoba("Ala", "Kowalska", 20);
Osoba r = a;
Osoba b = new Osoba("Ala", "Kowalska", 20);
Osoba c = new Osoba("Ola", "Kowalska", 30);
// HashSet oraz HashMap w działaniu korzystają z metod hashCode i equals.
boolean wynik; // wynik operacji add: jeśli element został dodany to true, a jeśli nie to false
Set<Osoba> zbior = new HashSet<>();
wynik = zbior.add(a);
System.out.println("a " + wynik);
wynik = zbior.add(r);
System.out.println("r " + wynik);
wynik = zbior.add(b);
System.out.println("b " + wynik);
wynik = zbior.add(c);
System.out.println("c " + wynik);
System.out.println();
System.out.println("Ilośc elementów: " + zbior.size());
for (Osoba osoba : zbior) {
System.out.println(osoba);
}
}
}
package p21_files;
import java.io.File;
import java.io.IOException;
public class Absolute {
public static void main(String[] args) {
String path;
if(args.length > 0)
path = args[0];
else path = "/katalog/../nowy.txt";
String path2 = "./a/b/c.zip";
File file = new File(path);
File file2 = new File(path2);
System.out.println("separatory: " + File.pathSeparator + " " +File.separator);
System.out.println("Argument : "+path);
System.out.println("Argument : "+path2);
System.out.println("Name : "+file.getName());
System.out.println("Name : "+file2.getName());
System.out.println("Absolute : "+file.getAbsolutePath());
System.out.println("Absolute : "+file2.getAbsolutePath());
String[] czlony = file.getName().split("\\.");
if(czlony.length >= 2)
System.out.println(czlony[czlony.length-1]);
try {
System.out.println("Canonical: "+file.getCanonicalPath());
System.out.println("Canonical: "+file2.getCanonicalPath());
} catch(IOException e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DStream {
// DirectoryStream nie wchodzi do podkatalogów
public static void main(String[] args) throws IOException {
Path dir = Paths.get("src");
DirectoryStream<Path> dstream = Files.newDirectoryStream(dir);
for(Path p : dstream) {
System.out.println(p);
}
System.out.println("======");
// W DirectoryStream nie działają wildcardy wielopoziomowe (nie schodzi do podkatalogów)
dstream = Files.newDirectoryStream(dir, "**.java");
for(Path p : dstream) {
System.out.println(p);
}
System.out.println("======");
dstream = Files.newDirectoryStream(dir.resolve("main/java/alx/p43_files"), "*.java");
for(Path p : dstream) {
System.out.println(p);
}
}
}
package p21_files;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Map;
import java.util.Set;
public class FilesProperties {
public static void main(String[] args) {
try {
String name;
if(args.length > 0)
name = args[0];
else name = "src";
Path start = Paths.get(name);
System.out.println("dir " + Files.isDirectory(start));
System.out.println("dirL " + Files.isDirectory(start, LinkOption.NOFOLLOW_LINKS));
System.out.println("exe " + Files.isExecutable(start));
System.out.println("hid " + Files.isHidden(start));
System.out.println("reg " + Files.isRegularFile(start));
System.out.println("regL" + Files.isRegularFile(start, LinkOption.NOFOLLOW_LINKS));
System.out.println("red " + Files.isReadable(start));
System.out.println("wri " + Files.isWritable(start));
System.out.println("sym " + Files.isSymbolicLink(start));
System.out.println("lmt " + Files.getLastModifiedTime(start));
System.out.println("lmtL" + Files.getLastModifiedTime(start, LinkOption.NOFOLLOW_LINKS));
System.out.println();
FileStore store = Files.getFileStore(start);
System.out.println("store total " + store.getTotalSpace() + " (" + store.getTotalSpace() / 1_000_000 + "M)");
System.out.println("store usable " + store.getUsableSpace() + " (" + store.getUsableSpace() / 1_000_000 + "M)");
System.out.println();
BasicFileAttributes attrs = Files.readAttributes(start, BasicFileAttributes.class);
System.out.println("A reg " + attrs.isRegularFile());
System.out.println("A time " + attrs.lastModifiedTime());
System.out.println("A other " + attrs.isOther());
DosFileAttributes dattrs = Files.readAttributes(start, DosFileAttributes.class);
System.out.println("D reg " + dattrs.isRegularFile());
System.out.println("D arc " + dattrs.isArchive());
System.out.println("Lista atrybutów");
Map<String, Object> pAttributes = Files.readAttributes(start, "*");
for(Map.Entry<String, Object> entry : pAttributes.entrySet()) {
System.out.println(entry.getKey() + " : "+entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Map;
import java.util.Set;
public class FilesProperties_Unix {
public static void main(String[] args) {
try {
String name;
if(args.length > 0)
name = args[0];
else name = "src";
//else name = "link_do_katalogu";
Path start = Paths.get(name);
System.out.println("dir " + Files.isDirectory(start));
System.out.println("dirL " + Files.isDirectory(start, LinkOption.NOFOLLOW_LINKS));
System.out.println("exe " + Files.isExecutable(start));
System.out.println("hid " + Files.isHidden(start));
System.out.println("reg " + Files.isRegularFile(start));
System.out.println("regL" + Files.isRegularFile(start, LinkOption.NOFOLLOW_LINKS));
System.out.println("red " + Files.isReadable(start));
System.out.println("wri " + Files.isWritable(start));
System.out.println("sym " + Files.isSymbolicLink(start));
System.out.println("lmt " + Files.getLastModifiedTime(start));
System.out.println("lmtL" + Files.getLastModifiedTime(start, LinkOption.NOFOLLOW_LINKS));
FileStore store = Files.getFileStore(start);
System.out.println("store total " + store.getTotalSpace() + " (" + store.getTotalSpace() / 1_000_000 + "M)");
System.out.println("store usable " + store.getUsableSpace() + " (" + store.getUsableSpace() / 1_000_000 + "M)");
BasicFileAttributes attrs = Files.readAttributes(start, BasicFileAttributes.class);
System.out.println("A reg " + attrs.isRegularFile());
System.out.println("A time " + attrs.lastModifiedTime());
System.out.println("A other " + attrs.isOther());
DosFileAttributes dattrs = Files.readAttributes(start, DosFileAttributes.class);
System.out.println("D reg " + dattrs.isRegularFile());
System.out.println("D arc " + dattrs.isArchive());
PosixFileAttributes pattrs = Files.readAttributes(start, PosixFileAttributes.class);
System.out.println("P reg " + pattrs.isRegularFile());
System.out.println("P own " + pattrs.owner());
System.out.println("P grp " + pattrs.group());
Set<PosixFilePermission> permissions = pattrs.permissions();
System.out.println("POSIX permissions: " + permissions);
Set<PosixFilePermission> permissions2 = Files.getPosixFilePermissions(start);
System.out.println("POSIX perms again: "+permissions2);
System.out.println("Lista atrybutów");
Map<String, Object> pAttributes = Files.readAttributes(start, "*");
for(Map.Entry<String, Object> entry : pAttributes.entrySet()) {
System.out.println(entry.getKey() + " : "+entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class Kopiowanie {
public static void main(String[] args) {
try {
String skad = "pan-tadeusz.txt";
String dokad = "kopia.txt";
Path pskad = Paths.get(skad);
Path pdokad = Paths.get(dokad);
System.out.println("Kopiuje");
Path copy = Files.copy(pskad, pdokad, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES, LinkOption.NOFOLLOW_LINKS);
System.out.println("Skopiowalem " + copy);
// kopiuje pojedyncze pliki, nie kopiuje katalogów rekurencyjnie
// dla katalogu - tworzy pusty katalog wynikowy
} catch(Exception e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.io.File;
public class ListFiles {
public static void main(String[] args) {
String start;
if(args.length > 0)
start = args[0];
else start = ".";
File dir = new File(start);
listFilesRec(dir, "");
}
public static void listFilesRec(File dir, String indent) {
if(dir.isDirectory()) {
String nextIndent = indent + " ";
File[] files = dir.listFiles();
if(files != null)
for(File file: files) {
System.out.print(indent);
if(file.isFile()) {
System.out.print("F ");
} else if(file.isDirectory()) {
System.out.print("D ");
} else {
System.out.print("S ");
}
System.out.println(file.getName());
listFilesRec(file, nextIndent);
}
}
}
}
package p21_files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Ls_Funkcyjnie {
public static void main(String[] args) {
Path dir = Paths.get(".");
try {
Files.list(dir)
.forEach(path -> System.out.println(path + " " + Files.isRegularFile(path)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.io.File;
public class Modyfikowanie {
public static void main(String[] args) {
File katalog = new File("nowy_katalog");
boolean jest = katalog.exists();
System.out.println(jest);
if(jest) {
System.out.println("Usuwam katalog");
katalog.delete();
} else {
System.out.println("Tworze nowy katalog");
katalog.mkdir();
}
}
}
package p21_files;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class Przenoszenie {
public static void main(String[] args) {
try {
String skad = "kopia.txt";
//String dokad = "przeniesione.txt";
String dokad = "/tmp/przeniesione.txt";
//String skad = "/home/patryk/kopiowanie/katalog";
//String dokad = "/home/patryk/katalog_nowy";
//String dokad = "/tmp/wynik";
Path pskad = Paths.get(skad);
Path pdokad = Paths.get(dokad);
System.out.println("Przenosze");
// To działa także przy przenoszeniu jednego pliku na inną partycję.
Path copy = Files.move(pskad, pdokad);
// ATOMIC_MOVE jest możliwy tylko w obrębie tej samej partycji, a nie zadziała gdy spróbujemy na inną
// Dodanie opcji ATOMIC_MOVE może spowodować wyjątek w sytuacjach, gdy bez tej opcji wszystko by zadziałało.
// Path copy = Files.move(pskad, pdokad, StandardCopyOption.ATOMIC_MOVE);
System.out.println("Przenioslem " + copy);
// przenosi pliki
// przenosi też katalogi wraz z zawartością
// ale tylko w obrębie tej samej partycji
} catch(Exception e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Sciezki {
public static void main(String[] args) {
//Path p = Paths.get("A/B/C");
//Path p = Paths.get("B/C");
Path p = Paths.get("/A/../B/C");
System.out.println(p);
System.out.println(p.isAbsolute());
System.out.println(p.getNameCount());
System.out.println(p.getFileName());
System.out.println(p.getName(0));
System.out.println(p.getName(1));
//System.out.println(p.getName(2));
FileSystem fs = p.getFileSystem();
System.out.println(fs + " " + fs.isReadOnly());
System.out.println(p.getRoot()); // null
Path parent = p.getParent();
System.out.println("parent: " + parent);
Path norm = p.normalize();
System.out.println("normalize: " + norm);
Path inny = Paths.get("A/B/D");
System.out.println("resolve " + p.resolve(inny));
System.out.println(inny.toAbsolutePath());
System.out.println(p.resolve(inny.toAbsolutePath()));
System.out.println(p.resolve("/home/users"));
System.out.println(p.toAbsolutePath().resolve("/home/users"));
System.out.println("abs res " + p.toAbsolutePath().resolve(inny));
// System.out.println("rel " + p.relativize(inny));
// System.out.println(p.normalize());
// System.out.println(p.normalize().relativize(inny));
System.out.println("Poprawny relativize: /A/B/C relativize /A/X/Y :");
System.out.println(Paths.get("/A/B/C").relativize(Paths.get("/A/X/Y")));
// to jest wyjatek, bo mieszam absolute i relative
//System.out.println(Paths.get("A/B/C").relativize(Paths.get("A/X/Y")));
//System.out.println(p.normalize().relativize(inny.toAbsolutePath()));
//System.out.println(p.toAbsolutePath().relativize(inny));
System.out.println(p.normalize().toAbsolutePath().relativize(inny.toAbsolutePath()));
}
}
package p21_files;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.nio.file.attribute.UserPrincipal;
import java.util.Arrays;
import java.util.Set;
public class Tworzenie {
public static void main(String[] args) {
try {
Path start = Paths.get("katalog");
Path path = Paths.get("ala");
if(! Files.exists(path)) {
Files.createDirectory(path);
}
Path path2 = Paths.get("ola");
Files.deleteIfExists(path2);
Files.createFile(path2);
// dziala pod Linuxem
// Path path21 = Paths.get("uprawnienia");
// Files.deleteIfExists(path21);
// Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrw-r--");
// Files.createFile(path21, PosixFilePermissions.asFileAttribute(perms));
Path path3 = Files.createTempDirectory("temp");
System.out.println(path3);
byte[] buf = new byte[10];
Arrays.fill(buf, (byte)68);
Path path4 = Files.createTempFile("PLIK", ".tmp");
System.out.println(path4);
//Files.write(path4, buf);
OutputStream stream = Files.newOutputStream(path4);
stream.write(buf);
stream.close();
Path path5 = Files.createTempDirectory(start, "bbb");
Path nowy = start.resolve("moj/nowy/katalog");
Path path6 = Files.createDirectories(nowy);
System.out.println(path6);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class Watchery {
// WatchService potrafi obserwowac tylko katalogi a nie pojedyncze pliki)
public static void main(String[] args) {
try {
Path start = Paths.get("katalog");
FileSystem fs = start.getFileSystem();
System.out.println("newWatchService()");
WatchService ws = fs.newWatchService();
System.out.println("Register:");
start.register(ws,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW);
System.out.println("Czekam");
WatchKey key = ws.take();
System.out.println("Jest "+key);
for(WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event "+event.kind().name() + " "+event.context());
}
System.out.println("Koniec");
} catch (Exception e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
public class WczytajWszystko {
public static void main(String[] args) {
Path plik = Paths.get("pan-tadeusz.txt");
Path plik2 = Paths.get("posortowane.txt");
try {
List<String> linie = Files.readAllLines(plik);
System.out.println("Pan Tadeusz ma " + linie.size() + " linii");
Collections.sort(linie);
Files.write(plik2, linie);
System.out.println("Gotowe");
} catch (IOException e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WczytajWszystko2 {
public static void main(String[] args) {
Path plik = Paths.get("pan-tadeusz.txt");
Path plik2 = Paths.get("posortowane2.txt");
try {
List<String> wyniki = Files.lines(plik)
.filter(s -> s.trim().length() > 10)
.map(s -> s.trim().toUpperCase())
.sorted()
.collect(Collectors.toList());
Files.write(plik2, wyniki);
System.out.println("Gotowe");
} catch (IOException e) {
e.printStackTrace();
}
}
}
package p21_files;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
// To schodzi do podkatalogów
public class Wizytowanie {
public static void main(String[] args) {
try {
Path start = Paths.get("src");
MojWizytor visitor = new MojWizytor();
Files.walkFileTree(start, visitor);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MojWizytor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
System.out.println("preVisitDirectory "+dir);
if("p10_klasy".equals(dir.getFileName().toString())) {
System.out.println("p10_klasy - omijam");
// Za pomocą wartości wynikowej sterujemy algorytmem - mówimy co ma robić dalej
return FileVisitResult.SKIP_SUBTREE;
} else
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
System.out.println("visitFile "+file.getFileName());
if("Kopiuj1.java".equals(file.getFileName().toString())) {
System.out.println("SKIP_SIBLINGS");
return FileVisitResult.SKIP_SIBLINGS;
} else
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
System.out.println("postVisitDirectory "+dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
System.out.println("visitFileFailed "+file);
return FileVisitResult.TERMINATE;
}
}
package p21_files;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class WizytowanieMatcher {
private static PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**moje**.java");
//private static PathMatcher pm = FileSystems.getDefault().getPathMatcher("regex:.*owa.*\\.java");
public static void main(String[] args) {
try {
Path start = Paths.get("src");
MojWizytorZMatcherem visitor = new MojWizytorZMatcherem();
Files.walkFileTree(start, visitor);
} catch (Exception e) {
e.printStackTrace();
}
}
private static class MojWizytorZMatcherem extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
System.out.println("preVisitDirectory "+dir);
if("p10_klasy".equals(dir.getFileName().toString())) {
System.out.println("p10_klasy - omijam");
return FileVisitResult.SKIP_SUBTREE;
} else
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
boolean pasuje = pm.matches(file);
System.out.println("visitFile "+file + " " + pasuje);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
System.out.println("visitFileFailed "+file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
System.out.println("postVisitDirectory "+dir);
return FileVisitResult.CONTINUE;
}
}
}
\ No newline at end of file
package p22_napisy;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class BudowanieNapisow_PomiarCzasu {
static String kolejneLiczby(int n) {
String napis = "";
for(int i = 1; i <= n; i++) {
napis += i + " ";
}
return napis;
}
static String kolejneLiczbyConcat(int n) {
String napis = "";
for(int i = 1; i <= n; i++) {
napis = napis.concat(i + " ");
}
return napis;
}
static String kolejneLiczbyCollector(int n) {
return IntStream.rangeClosed(1, n)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" "));
}
static String kolejneLiczbySB(int n) {
StringBuilder s = new StringBuilder();
for(int i = 1; i <= n; i++) {
s.append(i).append(' ');
}
return s.toString();
}
public static void main(String[] args) {
// sprawdzanie czasu wykonania
int[] dane1 = {25000, 50000, 100_000};
int[] dane2 = {25000, 50000, 100_000, 1_000_000, 10_000_000};
int[] dane3 = {25000, 50000, 100_000, 1_000_000, 10_000_000, 100_000_000};
System.out.println("Wersja String +=");
System.out.println(kolejneLiczby(10));
for(int n : dane1) {
System.out.println("n = " + n + "...");
long start = System.currentTimeMillis();
String wynik = kolejneLiczby(n);
long koniec = System.currentTimeMillis();
System.out.println(" Dla n = " + n + " trwało " + (koniec - start) + "ms");
System.out.println(" Napis ma długość " + wynik.length());
}
System.out.println();
System.out.println("Wersja String concat");
System.out.println(kolejneLiczbyConcat(10));
for(int n : dane1) {
System.out.println("n = " + n + "...");
long start = System.currentTimeMillis();
// start = System.nanoTime();
String wynik = kolejneLiczbyConcat(n);
long koniec = System.currentTimeMillis();
System.out.println(" Dla n = " + n + " trwało " + (koniec - start) + "ms");
System.out.println(" Napis ma długość " + wynik.length());
}
System.out.println();
System.out.println("Wersja Stream / collector");
System.out.println(kolejneLiczbyCollector(10));
for(int n : dane2) {
System.out.println("n = " + n + "...");
long start = System.currentTimeMillis();
String wynik = kolejneLiczbyCollector(n);
long koniec = System.currentTimeMillis();
System.out.println(" Dla n = " + n + " trwało " + (koniec - start) + "ms");
System.out.println(" Napis ma długość " + wynik.length());
}
System.out.println();
System.out.println("Wersja StringBuilder");
System.out.println(kolejneLiczbySB(10));
for(int n : dane3) {
System.out.println("n = " + n + "...");
long start = System.currentTimeMillis();
String wynik = kolejneLiczbySB(n);
long koniec = System.currentTimeMillis();
System.out.println(" Dla n = " + n + " trwało " + (koniec - start) + "ms");
System.out.println(" Napis ma długość " + wynik.length());
}
System.out.println();
}
}
package p22_napisy;
public class InnaKlasa {
public static String dajStringaZKodu() {
return "Ala ma kota";
}
public static String dajStringaNowego() {
return new String("Ala ma kota");
}
}
package p22_napisy;
public class OperacjeNaStringach {
public static void main(String[] args) {
String napis = "Ala ma kota";
System.out.println(napis);
napis.concat(" Filemona");
napis.replace("Ala", "Alicja");
System.out.println(napis); // napis się nie zmienił
System.out.println();
napis = napis.concat(" Bonifacego");
System.out.println(napis); // teraz zmieniony
System.out.println("\nMetody informacyjne");
System.out.println(napis.length());
System.out.println(napis.charAt(2)); // numeracja od 0
//EXN System.out.println(napis.charAt(30));
System.out.println(napis.codePointAt(2)); // kod Unicode
System.out.println("\nSprawdzanie czy zawiera fragment");
// istotna jest też wielkośc liter
System.out.println(napis.contains("kot"));
System.out.println(napis.startsWith("Ala"));
System.out.println(napis.endsWith("kot"));
System.out.println(napis.equals("ala ma kota bonifacego")); // F
// a to nie patrzy na wielkość liter
System.out.println(napis.equalsIgnoreCase("ala ma kota bOnIfAcEgO")); // T
System.out.println("\nWyszukiwanie");
System.out.println(napis.indexOf("ma"));
System.out.println(napis.indexOf("pies")); // -1
System.out.println(napis.indexOf('a')); //2
System.out.println(napis.indexOf('a', 3)); //5 bo szukam litery a od pozycji nr 3
System.out.println(napis.lastIndexOf('a')); // ostatnie a w napisie
System.out.println("\nMetody zwracające zmieniony napis");
System.out.println(napis.concat(" i jeszcze psa Reksia"));
System.out.println("|"+napis.substring(7, 15)+"|"); // od 7 włącznie, do 15 wyłączając; 15-7 = 8, 8 to jest długość wynikowego słowa
System.out.println("|"+napis.substring(7)+"|"); // od 7 do końca
System.out.println(napis.toLowerCase());
System.out.println(napis.toUpperCase());
// replace zamienia wszystkie wystąpienia
System.out.println(napis.replace(' ', '_'));
System.out.println(napis.replace("ma", "posiada"));
// Działa na wyrażeniach regularnych.
// Ten przykład zamienia pierwsze litery słów (po spacjach)
System.out.println(napis.replaceAll(" .", " X"));
}
}
package p22_napisy;
public class ParametryString {
public static void main(String[] args) {
String a = "Ala";
System.out.println("a1 = " + a);
m(a);
System.out.println("a2 = " + a);
// String is immutable
}
static void m(String c) {
System.out.println("c1 = " + c);
c += " ma kota";
System.out.println("c2 = " + c);
// tak naprawdę jest tworzony nowy obiekt String: c = new String("Ala" + " ma kota")
// a oryginalny obiekt, na który wskazuje zmienna a, nie zmienia się
}
}
package p22_napisy;
import java.util.Objects;
public class Porownywanie {
public static void main(String[] args) {
String ala = "Ala";
final String final_ala = "Ala";
String a = "Ala ma kota";
String b = "Ala ma kota";
String c = "Ala" + " ma kota";
String d = final_ala + " ma kota";
String e = InnaKlasa.dajStringaZKodu();
String f = new String(a);
String g = ala + " ma kota";
// tak samo jest dla danych wczytywanych z zewnętrznych źródeł: konsola, plik, baza danych
System.out.println("==");
System.out.println(a == "Ala ma kota");
System.out.println(a == a);
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a == d);
System.out.println(a == e);
System.out.println(a == f);
System.out.println(a == g);
System.out.println();
System.out.println("intern");
// intern zwraca referencję do stringa o takiej samej treści, ale pochodzącego z puli stringów
// jeśli w puli jeszcze go nie było, to dodawany
System.out.println(a.intern() == f.intern());
System.out.println();
System.out.println("equals");
System.out.println(a.equals(a));
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(a.equals(d));
System.out.println(a.equals(e));
System.out.println(a.equals(f));
System.out.println(a.equals(g));
System.out.println("Ala ma kota".equals(g));
System.out.println(Objects.equals(a, g));
}
}
package p23_generyki.kolekcje;
import java.util.ArrayList;
import java.util.List;
public class DeklaracjeGeneryczne {
public static void main(String[] args) {
List l1 = new ArrayList();
ArrayList l2 = new ArrayList();
List<String> l3 = new ArrayList<String>();
List<String> l4 = new ArrayList<>(); // diamond operator od Javy 7
List<String> l5 = new ArrayList();
List l6 = new ArrayList<>(); // lista Object-ów
List l6a = new ArrayList<String>();
//NK List<> l7 = new ArrayList<String>();
List<List<Integer>> l8 = new ArrayList<>();
//NK List<List<Integer>> l9 = new ArrayList<<>>();
//NK List<List<Integer>> l10 = new ArrayList<List<>>();
List<List<Integer>> l11 = new ArrayList<List<Integer>>();
//NK List<Object> l12 = new ArrayList<String>();
//NK List<String> l13 = new ArrayList<Object>();
List<? extends Object> l14 = new ArrayList<String>();
List<?> l15 = new ArrayList<String>(); // sam ? jest równoważny ? extends Object
//NK List<?> foo1 = new ArrayList<? extends Number>();
//NK List<?> foo2 = new ArrayList<? super Number>();
//NK List<?> foo3 = new ArrayList<?>();
}
}
package p23_generyki.kolekcje;
import java.util.ArrayList;
import java.util.List;
public class OszukiwanieGenerykow {
public static void main(String[] args) {
List<String> lista = new ArrayList<String>();
Integer i = 99;
lista.add("Ala");
//NK lista.add(7);
//NK lista.add(i);
List oszust = lista;
oszust.add("Ola");
oszust.add(i); // tu nie jeszcze błędu
oszust.add(8);
System.out.println(lista.size());
System.out.println(lista);
for(Object o : lista) {
System.out.println(o + " obiekt klasy " + o.getClass().getSimpleName());
}
System.out.println();
for(String s : lista) { // dopiero tu jest błąd CCE gdy dojdziemy do Integera
System.out.println(s);
}
}
}
package p23_generyki.kolekcje;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OszukiwanieGenerykow2 {
static void metodaOszukujaca(List<String> lista) {
List oszust = lista;
oszust.add(new Integer(113));
}
public static void main(String[] args) {
List<String> lista1 = new ArrayList<String>();
lista1.add("Ala");
lista1.add("Ola");
System.out.println(lista1);
metodaOszukujaca(lista1);
System.out.println(lista1);
System.out.println();
List<String> lista2 = new ArrayList<String>();
List<String> listaZabezpieczona = Collections.checkedList(lista2, String.class);
// checkedList daje zachowanie typu "fail-fast" - od razu w momencie wykonanie niepoprawnej operacji następuje wyjątek
lista2.add("Ela");
listaZabezpieczona.add("Ula");
// listaZabezpieczona jest "widokiem" listy oryginalnej
// zmiany dokonywane poprzez jedną zmienną są widziane przez drugą
System.out.println(lista2);
System.out.println(listaZabezpieczona);
metodaOszukujaca(listaZabezpieczona); // teraz będzie wyjątek już przy próbie dodania niezgodnego elementu
System.out.println(lista2);
}
}
package p23_generyki.kolekcje;
import java.util.ArrayList;
import java.util.List;
public class Polimorfizm1 {
static double testPojedynczego(Number arg) {
return arg.doubleValue();
}
static double suma1(List<Number> lista) {
double wynik = 0.0;
for (Number number : lista) {
wynik += number.doubleValue();
}
return wynik;
}
static void modyfikuj1(List<Number> lista) {
lista.add(Long.valueOf(10_000_000_000L));
}
static double suma2(List<? extends Number> lista) {
//NK lista.add(Long.valueOf(10_000_000_000L));
double wynik = 0.0;
for (Number number : lista) {
wynik += number.doubleValue();
}
return wynik;
}
static void modyfikuj2(List<? super Long> lista) {
lista.add(Long.valueOf(10_000_000_000L));
}
/** Zamienia pierwszy element z ostatnim i zwraca ich średnią */
static <T extends Number> double sredniaZZamiana(List<T> lista) {
T pierwszy = lista.get(0);
T ostatni = lista.get(lista.size()-1);
lista.set(0, ostatni);
lista.set(lista.size()-1, pierwszy);
return (pierwszy.doubleValue() + ostatni.doubleValue()) / 2.0;
}
/* to się nie kompilowało, bo wewnątrz funkcji o elementach listy było wiadomo tlyko,
* że są to jakieś Numbery - a to za mało aby wpisać do listy niewiadomoczego
* Lista mogłaby być listą Integerów, a zmienne pierwszy i ostatni sa typu Number. */
/*
static double sredniaZZamiana2(List<? extends Number> lista) {
Number pierwszy = lista.get(0);
Number ostatni = lista.get(lista.size()-1);
lista.set(0, ostatni);
lista.set(lista.size()-1, pierwszy);
return (pierwszy.doubleValue() + ostatni.doubleValue()) / 2.0;
}
*/
/*
static double sredniaZZamiana3(List<? super Number> lista) {
Number pierwszy = lista.get(0);
Number ostatni = lista.get(lista.size()-1);
lista.set(0, ostatni);
lista.set(lista.size()-1, pierwszy);
return (pierwszy.doubleValue() + ostatni.doubleValue()) / 2.0;
}
*/
/* //Takiej składni nie ma:
static <T super Number> void metoda3(List<T> lista) {
}
*/
// Sam znak zapytania jest równoważny <? extends Object> - co nie wnosi żadnej wiedzy
// "lista czegokolwiek"
// To nie jest to samo co List<Object> !!!
// bo wtedy nie dałoby się przekazać np. List<Integer>
// To też nie jest to samo co po prostu List.
static int metoda4a(List<Object> lista) {
return lista == null ? 0 : lista.size();
}
static int metoda4(List<?> lista) {
return lista == null ? 0 : lista.size();
}
static void metoda5(List<?> lista) {
// z takiej listy można odczytywać elementy - są dla nas Objectami
Object o = lista.get(0);
// do takiej listy nie możemy wstawić niczego innego niż null
// być może jest to lista Integerów? albo Stringów? nie wiadomo - na wszelki wypadek kompilator zabrania wstawiać czegokolwiek-
//NK lista.add(new Object());
// null pasuje do każdego typu
lista.add(null);
}
public static void main(String[] args) {
double wynik;
Number nn = new Long(123L);
Integer ii = new Integer(321);
wynik = testPojedynczego(nn);
System.out.println(wynik);
wynik = testPojedynczego(ii);
System.out.println(wynik);
System.out.println();
List<Number> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
System.out.println(numbers);
List<Integer> ints = new ArrayList<>();
ints.add(11);
ints.add(21);
ints.add(31);
ints.add(41);
System.out.println(ints);
wynik = suma1(numbers);
System.out.println(wynik);
System.out.println();
// Gdy metoda oczekuje listy Numberów, nie można przekazać listy Integerów
// wynik = suma1(ints);
// System.out.println(wynik);
// System.out.println();
// Do listy Numberów można dodać Longa - OK
modyfikuj1(numbers);
System.out.println(numbers);
// Gdyby można było przekazywać, to to wywołanie zepsułoby listę Integerów
// - na takiej liście znalazłby się Long
// modyfikuj1(ints);
// System.out.println(ints);
System.out.println();
// Nie wolno też przypisać List<Integer> na zmienną List<Number>
//NK List<Integer> ints2 = numbers;
wynik = suma2(numbers);
System.out.println(wynik);
System.out.println();
wynik = suma2(ints);
System.out.println(wynik);
System.out.println();
modyfikuj2(numbers);
System.out.println(numbers);
// modyfikuj2(ints);
// System.out.println(ints);
//NK metoda4a(ints); // List<Object>
metoda4(ints); // List<?>
}
}
package p23_generyki.kolekcje;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Polimorfizm2 {
// Przykład funkcji, która zadziała dla dowolnej listy - typ elementu w ogóle nieistotny
static void usunOstatni(List<?> lista) {
int size = lista.size();
if(size > 0) {
lista.remove(size-1);
}
}
// Do tak zadeklarowanej funkcji będzie można przekazać tylko listę Objectów
// (konkretnie List<Object>, nic innego)
static void usunOstatniZle(List<Object> lista) {
int size = lista.size();
if(size > 0) {
lista.remove(size-1);
}
}
public static void main(String[] args) {
List<String> listaStringow = new ArrayList<>();
List<Integer> listaIntow = new ArrayList<>();
List<LocalDate> listaDat = new ArrayList<>();
List<?> lista1 = new ArrayList<>();
// do tak zadeklarowanej listy nie można dodać niczego
// lista1.add("ala");
// OK, można dodać nulla
lista1.add(null);
// Dlaczego?
// List<?> jest równoważna takiej:
List<? extends Object> lista2 = new ArrayList<>();
// lista2.add("ala");
lista2.add(null);
// To znaczy, że na taką zmienną można wpisać dowolną listę:
lista2 = listaDat;
// czy można wpisać Stringa na taką listę?
// kompilator zabrania wstawiać czegokolwiek - chodzi o tym zmiennej, a nie listy w pamięci
// lista2.add("ala");
lista2 = listaIntow;
lista1 = listaDat;
lista1 = listaIntow;
for (Object object : lista1) {
// podczas czytania elementy widzimy jako Objecty
}
Class<Polimorfizm2> klasa1 = Polimorfizm2.class;
//NK Class<Polimorfizm2> klasa2 = String.class;
Class<?> klasa3 = Polimorfizm2.class;
Class<?> klasa4 = String.class;
Class<? extends Number> klasa5;
klasa5 = Integer.class;
klasa5 = Long.class;
klasa5 = Number.class;
//NK klasa5 = String.class;
}
}
package p23_generyki.kolekcje;
import java.util.Arrays;
public class Polimorfizm3_Tablice {
static double suma(Number[] t) {
double suma = 0.0;
for (Number number : t) {
suma += number.doubleValue();
}
return suma;
}
static void modyfikuj(Number[] t) {
t[0] = new Long(10_000_000_000L);
}
public static void main(String[] args) {
Number[] numbers = new Number[] {10, 20, 30, 40, 50};
Integer[] ints = new Integer[] {11, 21, 31, 41};
Number[] numbers2 = ints;
//NK Integer[] ints2 = numbers2;
double wynik;
wynik = suma(numbers);
System.out.println(wynik);
// jesli chodzi o tablicę, to tablica podklas jest traktowana jak podklasa tablicy nadklas
wynik = suma(ints);
System.out.println(wynik);
System.out.println();
modyfikuj(numbers);
System.out.println(Arrays.toString(numbers));
modyfikuj(ints);
System.out.println(Arrays.toString(ints));
}
}
package p23_generyki.kolekcje;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StaraJava {
public static void main(String[] args) {
// Tak się używało list i innych kolekcji w wersjach Javy < 5
List lista = new ArrayList();
lista.add("Ala");
lista.add("Ola");
lista.add("Ela");
// lista.add(new Integer(133));
System.out.println(lista);
Iterator it = lista.iterator();
while(it.hasNext()) {
String elt = (String)it.next();
System.out.println(elt);
}
String imie = (String)lista.get(1);
System.out.println(imie);
}
}
package p23_generyki.techniczne;
public class GdzieMoznaUzywacGenerykow {
private static class Box<T> {
// Parametru generycznego można używać:
// typ zmiennej instanyjnej
T x, y;
// typ paraterów i wyniku metod instancyjnych:
T metoda(T parametr, String innyParametr) {
// typ zmiennej lokalnej wewnątrz metody instancyjnej:
T zmienna = parametr;
if(zmienna == null) {
zmienna = x;
}
return zmienna;
}
// Parametru generycznego nie można używać:
// w kontekście statycznym
// static T statyczna;
// static T metodaStatyczna(T arg) {
// return arg;
// }
static void normalnaMetodaStatyczna() {
// T zmienna = null;
}
void test(T arg1, Object arg2) {
// Parametru generycznego nie można używać również w poleceniach,
// które wymagałyby znajomości tego typu w runtajmie:
// System.out.println(T.class);
System.out.println(x.getClass());
// if(arg1 instanceof T) {
//
// }
//
// if(arg2 instanceof T) {
//
// }
// rzutowanie można zapisać, ale nie ma jak sprawdzić w instaceof czy to bezpieczne
T t = (T)arg2;
System.out.println(t);
}
}
}
package p23_generyki.techniczne;
import java.time.LocalDate;
public class MetodyInstancyjne<A> {
// Metody mogą być parametryzowane typami generycznymi - każda niezależnie.
// Te parametry nie mają nic wspólnego z parametreami na poziomie klasy, w której jesteśmy (gdyby takie były).
A aaa(A a) {
System.out.println("a = " + a);
return a;
}
// A jest parametrem ustalonym na poziomie klasy, a B na poziomie metody
<B> B bbb(A a, B b) {
System.out.println("a = " + a + " , b = " + b);
return b;
}
// Parametr podany na poziomie metody może przesłonić parametr podany na poziomie klasy
<A> A ccc(A a) {
System.out.println("a = " + a);
return a;
}
public static void main(String[] args) {
MetodyInstancyjne<String> instancjaString = new MetodyInstancyjne<>();
MetodyInstancyjne<Integer> instancjaInteger = new MetodyInstancyjne<>();
String s1 = instancjaString.aaa("Ala");
System.out.println(s1);
// LocalDate s2 = instancjaString.aaa(LocalDate.now());
// Na pierwszym parametrze musi być String,
// na drugim może być cokolwiek. Typ metody mówi, że wynik jest tego samego typu, co drugi argument.
String s3 = instancjaString.bbb("Ala", "Ola");
System.out.println(s3);
LocalDate s4 = instancjaString.bbb("Ala", LocalDate.now());
System.out.println(s4);
LocalDate s5 = instancjaInteger.bbb(123, LocalDate.now());
System.out.println(s5);
LocalDate s6 = instancjaString.ccc(LocalDate.now());
System.out.println(s6);
}
}
package p23_generyki.techniczne;
import java.util.Optional;
import p23_generyki.v2_generics.Para;
public class MetodyStatyczne {
// Metody mogą być parametryzowane typami generycznymi - każda niezależnie.
// Te parametry nie mają nic wspólnego z parametreami na poziomie klasy, w której jesteśmy (gdyby takie były).
// Można to robić zarówno dla metod statycznych (w praktyce znacznie częściej),
// jak i dla instancyjnych.
static <T> T ident(T arg) {
return arg;
}
static <T> Optional<T> opakuj(T arg) {
if (arg == null) {
return Optional.empty();
} else {
return Optional.of(arg);
}
}
static <T> T dajNulla() {
return null;
}
static <L, R> void wypisz(Para<L,R> para) {
System.out.println(para);
}
static <L, R> Para<R,L> zamien(Para<L,R> para) {
return new Para<>(para.getPrawy(), para.getLewy());
}
public static void main(String[] args) {
String s, z;
s = "Ala";
z = ident(s);
System.out.println(z);
System.out.println(opakuj(s));
System.out.println(opakuj(null));
}
}
package p23_generyki.v1_object;
import java.util.ArrayList;
public class KolekcjeBezGenerykow {
public static void main(String[] args) {
ArrayList lista = new ArrayList();
lista.add("Ala");
lista.add("Ola");
lista.add(new Integer(50));
System.out.println(lista);
// W momencie wyjęcia obiektu z kolekcji, trzeba było dokonać rzutowania.
String imie = (String)lista.get(1);
System.out.println(imie);
//EXN CCE imie = (String) lista.get(2);
// System.out.println(imie);
}
}
package p23_generyki.v1_object;
import java.util.Objects;
/* Wersja bez typów generycznych - programowanie jak w Javie <= 1.4 */
public class Para {
private Object lewy;
private Object prawy;
public Para() {
}
public Para(Object lewy, Object prawy) {
this.lewy = lewy;
this.prawy = prawy;
}
public Object getLewy() {
return lewy;
}
public void setLewy(Object lewy) {
this.lewy = lewy;
}
public Object getPrawy() {
return prawy;
}
public void setPrawy(Object prawy) {
this.prawy = prawy;
}
@Override
public String toString() {
return "<" + lewy + ", " + prawy + ">";
}
@Override
public int hashCode() {
return Objects.hash(lewy, prawy);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Para other = (Para) obj;
return Objects.equals(lewy, other.lewy) && Objects.equals(prawy, other.prawy);
}
}
package p23_generyki.v1_object;
import java.util.Objects;
/* Wersja bez typów generycznych - programowanie jak w Javie <= 1.4.
*
* Istnieje możliwość tworzenia osobnych klas w zlaeżnośc iod tego, co będą miały w środku.
* Ale to pracochłonne i redundantne.
*/
public class ParaIntegerow {
private Integer lewy;
private Integer prawy;
public ParaIntegerow() {
}
public ParaIntegerow(Integer lewy, Integer prawy) {
this.lewy = lewy;
this.prawy = prawy;
}
public Integer getLewy() {
return lewy;
}
public void setLewy(Integer lewy) {
this.lewy = lewy;
}
public Integer getPrawy() {
return prawy;
}
public void setPrawy(Integer prawy) {
this.prawy = prawy;
}
@Override
public String toString() {
return "<" + lewy + ", " + prawy + ">";
}
@Override
public int hashCode() {
return Objects.hash(lewy, prawy);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParaIntegerow other = (ParaIntegerow) obj;
return Objects.equals(lewy, other.lewy) && Objects.equals(prawy, other.prawy);
}
}
package p23_generyki.v1_object;
import java.time.LocalDate;
public class Test1 {
public static void main(String[] args) {
Para para1 = new Para("Ala", 33);
System.out.println(para1);
// problem1: odczytując dostaję ogólny typ Object i muszę dokonać rzutowania:
String imie = (String) para1.getLewy();
int wiek = (Integer) para1.getPrawy();
System.out.println(imie + " : " + wiek);
// problem2: brak kontroli typów podczas zapisywania (przekazywania parametrów):
para1.setPrawy(LocalDate.now());
// łatwo się pomylić co do typu obiektu
wiek = (Integer) para1.getPrawy(); // EXN
System.out.println(wiek);
}
}
package p23_generyki.v2_generics;
import java.util.Objects;
/*
* Zazwyczaj nazwy parametrów typowych są jednoliterowe (T, R, ...),
* ale z punktu widzenia składni Javy są to po prostu identyfikatory.
*/
public class Para<Lewy, Prawy> {
private Lewy lewy;
private Prawy prawy;
public Para() {
}
public Para(Lewy lewy, Prawy prawy) {
this.lewy = lewy;
this.prawy = prawy;
}
public Lewy getLewy() {
return lewy;
}
public void setLewy(Lewy lewy) {
this.lewy = lewy;
}
public Prawy getPrawy() {
return prawy;
}
public void setPrawy(Prawy prawy) {
this.prawy = prawy;
}
@Override
public String toString() {
return "<" + lewy + ", " + prawy + ">";
}
@Override
public int hashCode() {
return Objects.hash(lewy, prawy);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Para other = (Para) obj;
return Objects.equals(lewy, other.lewy) && Objects.equals(prawy, other.prawy);
}
}
package p23_generyki.v2_generics;
public class Test1 {
public static void main(String[] args) {
Para<String, Integer> para1 = new Para<String, Integer>("Ala", 33);
System.out.println(para1);
// Podczas odczytywania nie trzeba rzutować.
String imie = para1.getLewy();
Integer wiek = para1.getPrawy();
System.out.println(imie + " : " + wiek);
// Tym razem taka próba się nie skompiluje
// para1.setPrawy(LocalDate.now());
// Poszczególne instancje mogą mieć różnie ustalone parametry generyczne.
Para<Integer, Integer> para2 = new Para<>();
para2.setLewy(13);
para2.setPrawy(13);
System.out.println(para2);
System.out.println();
// Na etapie kompilacji zmienne para1 i para2 są różnego typu
//NK para1 = para2;
// Jednak w runtime klasa tych obiektów jest taka sama.
System.out.println(para1.getClass());
System.out.println(para2.getClass());
System.out.println(para1.getClass() == para2.getClass());
}
}
package p23_generyki.v3_para_liczb_bez_generykow;
import java.util.Objects;
/*
* Zazwyczaj nazwy parametrów typowych są jednoliterowe (T, R, ...),
* ale z punktu widzenia składni Javy są to po prostu identyfikatory.
*/
public class Para<Lewy, Prawy> {
private Lewy lewy;
private Prawy prawy;
public Para() {
}
public Para(Lewy lewy, Prawy prawy) {
this.lewy = lewy;
this.prawy = prawy;
}
public Lewy getLewy() {
return lewy;
}
public void setLewy(Lewy lewy) {
this.lewy = lewy;
}
public Prawy getPrawy() {
return prawy;
}
public void setPrawy(Prawy prawy) {
this.prawy = prawy;
}
@Override
public String toString() {
return "<" + lewy + ", " + prawy + ">";
}
@Override
public int hashCode() {
return Objects.hash(lewy, prawy);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Para other = (Para) obj;
return Objects.equals(lewy, other.lewy) && Objects.equals(prawy, other.prawy);
}
}
package p23_generyki.v3_para_liczb_bez_generykow;
import java.util.Objects;
public class ParaLiczb {
private Number lewy;
private Number prawy;
public ParaLiczb() {
}
public ParaLiczb(Number lewy, Number prawy) {
this.lewy = lewy;
this.prawy = prawy;
}
public Number getLewy() {
return lewy;
}
public void setLewy(Number lewy) {
this.lewy = lewy;
}
public Number getPrawy() {
return prawy;
}
public void setPrawy(Number prawy) {
this.prawy = prawy;
}
@Override
public String toString() {
return "<" + lewy + ", " + prawy + ">";
}
@Override
public int hashCode() {
return Objects.hash(lewy, prawy);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParaLiczb other = (ParaLiczb) obj;
return Objects.equals(lewy, other.lewy) && Objects.equals(prawy, other.prawy);
}
// Wiedza, że elementy są jakimiś liczbami daje mi możliwości definiowania operacji matematycznych,
// przykładowo średnia.
// Nie byłoby to możliwe w klasie takiej jak Para
public double getSrednia() {
return (lewy.doubleValue() + prawy.doubleValue()) / 2.0;
}
}
package p23_generyki.v3_para_liczb_bez_generykow;
public class Test2 {
public static void main(String[] args) {
ParaLiczb para1 = new ParaLiczb(new Integer(13), new Integer(3000));
// Przy takim podejściu mogę odczytywane wartości potraktować jak Number:
Number lewy = para1.getLewy();
// Ale nie mogę założyć że to będzie np. Integer
// Integer lewyi = para1.getLewy();
Integer lewyi = (Integer) para1.getLewy();
System.out.println(para1.getSrednia());
// Mogę też wstawić dowolny Number, kompilator nie sprawdzi czy to Integer
// A jeśli chciałbym, aby w tej konkretnej parze były Integery?
para1.setLewy(new Double(3.14));
System.out.println(para1.getSrednia());
// Jednocześnie uzywanie ogólnej Pary nie daje mi wiedzy o tym, że tam są na pewno liczby
Para<Integer, Integer> para = new Para<>(3,4);
System.out.println(para);
// System.out.println(para.getSrednia());
}
}
package p23_generyki.v4_para_liczb_extends;
import java.util.Objects;
// Za pomocą ograniczeń "extends" oraz "super" możemy wymusić, że parametr typowy
// spełnia pewne warunki.
// W tym przypadku T extends Number oznacza, że T to może byc Number, Integer, Double, BigDecimal itd., ale nie String, Object czy inne typy
public class ParaLiczb<T extends Number> {
private T lewy;
private T prawy;
public ParaLiczb() {
}
public ParaLiczb(T lewy, T prawy) {
this.lewy = lewy;
this.prawy = prawy;
}
public T getLewy() {
return lewy;
}
public void setLewy(T lewy) {
this.lewy = lewy;
}
public T getPrawy() {
return prawy;
}
public void setPrawy(T prawy) {
this.prawy = prawy;
}
@Override
public String toString() {
return "<" + lewy + ", " + prawy + ">";
}
@Override
public int hashCode() {
return Objects.hash(lewy, prawy);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParaLiczb other = (ParaLiczb) obj;
return Objects.equals(lewy, other.lewy) && Objects.equals(prawy, other.prawy);
}
// Wiedza, że elementy są jakimiś liczbami daje mi możliwości definiowania operacji matematycznych,
// przykładowo średnia.
// Nie byłoby to możliwe w klasie takiej jak Para
public double getSrednia() {
return (lewy.doubleValue() + prawy.doubleValue()) / 2.0;
}
}
package p23_generyki.v4_para_liczb_extends;
import java.math.BigDecimal;
public class Test2 {
public static void main(String[] args) {
ParaLiczb<Integer> para1 = new ParaLiczb<>(new Integer(13), new Integer(3000));
ParaLiczb<Integer> para1a = new ParaLiczb<>(13, 3000);
ParaLiczb<Integer> para1b = new ParaLiczb<>(Integer.valueOf(13), Integer.valueOf(3000));
System.out.println(para1);
Number lewy = para1.getLewy();
Integer lewyi = para1.getLewy();
//NK para1.setLewy(new Double(3.14));
para1.setLewy(44);
// Wiedząc, że jest to para liczb, mogę korzystać z operacji matematycznych
double avg = para1.getSrednia();
System.out.println(avg);
ParaLiczb<BigDecimal> para2 = new ParaLiczb<>(BigDecimal.ONE, new BigDecimal("3.99"));
System.out.println(para2);
avg = para2.getSrednia();
System.out.println(avg);
// Wymagane jest, aby typ był Number albo jego podklasą
//NK ParaLiczb<String> para3 = new ParaLiczb<>();
}
}
package p24_refleksja;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.Scanner;
public final class PokazRefleksji {
private final Scanner sc;
private Class<?> c = null;
private Object o = null;
PokazRefleksji() {
sc = new Scanner(System.in);
}
private String menu() {
System.out.println();
System.out.println("Current class: " + c);
System.out.println("Current object: " + o);
System.out.println("\nChoose action:");
System.out.println("q - quit");
if(c == null) {
System.out.println("c - choose class");
} else {
System.out.println("c - change class");
System.out.println("p - print general info about current class");
System.out.println("lf - list fields of current class");
System.out.println("lm - list methods of current class");
System.out.println("lc - list constructors of current class");
System.out.println("o - create object ()");
System.out.println("oc - create object using constructor");
}
return sc.nextLine().trim().toLowerCase();
}
private void changeClass() {
System.out.println("Give the full class name (with package):");
String className = sc.nextLine();
try {
c = Class.forName(className);
System.out.println("Class " + className + " has been loaded.");
o = null;
} catch (ClassNotFoundException e) {
System.out.println("Class " + className + " can not been loaded.");
System.out.println("Exception: " + e);
}
}
private void printInfo() {
System.out.println(c.toGenericString());
System.out.println("Full name: " + c.getName());
System.out.println("Simple name: " + c.getSimpleName());
System.out.println("Canonical name: " + c.getCanonicalName());
if(c.getSuperclass() != null) {
System.out.println("superclass: " + c.getSuperclass().getName());
}
if(c.getEnclosingClass() != null) {
System.out.println("enclosing class: " + c.getEnclosingClass().getName());
}
if(c.isArray()) {
System.out.println("This is array of " + c.getComponentType());
}
}
private void listFields() {
System.out.println("All accessible fields:");
for(Field field : c.getFields()) {
describeField(field);
}
System.out.println();
System.out.println("All fields declared in this class:");
for(Field field : c.getDeclaredFields()) {
describeField(field);
}
}
private void listMethods() {
System.out.println("All accessible methods:");
for(Method method : c.getMethods()) {
describeMethod(method);
}
System.out.println();
System.out.println("All methods declared in this class:");
for(Method method : c.getDeclaredMethods()) {
describeMethod(method);
}
}
private void listConstructors() {
System.out.println("All accessible methods:");
for(Constructor<?> constr : c.getConstructors()) {
describeConstructor(constr);
}
System.out.println();
}
private void describeField(Field field) {
System.out.print(" * " + field.getName() + " : " + field.getGenericType());
System.out.println(" / " + Modifier.toString(field.getModifiers()));
}
private void describeMethod(Method method) {
System.out.print(" * " + method.getName());
System.out.println(" / " + Modifier.toString(method.getModifiers()));
System.out.println(" parameters:");
for (Parameter parameter : method.getParameters()) {
System.out.println(" - " + parameter.getName() + " : " + parameter.getType());
}
System.out.println(" result type: " + method.getReturnType());
}
private void describeConstructor(Constructor<?> constr) {
System.out.print(" * " + constr);
System.out.println(" / " + Modifier.toString(constr.getModifiers()));
System.out.println(" parameters:");
for (Parameter parameter : constr.getParameters()) {
System.out.println(" - " + parameter.getName() + " : " + parameter.getType());
}
}
private void createObject() {
try {
Constructor<?> defaultConstructor = c.getConstructor();
o = defaultConstructor.newInstance();
System.out.println("New object has been created");
System.out.println(o);
} catch (NoSuchMethodException e) {
System.out.println("This class has no default constructor. " + e);
} catch (Exception e) {
System.out.println(e);
}
}
private void invokeConstructor() {
Constructor<?>[] constructors = c.getConstructors();
if(constructors.length == 0) {
System.out.println("No constructors available.");
return;
}
System.out.println("Choose one of the constructors:");
for (int i = 0; i < constructors.length; i++) {
System.out.printf(" * %2d : %s\n", i, constructors[i]);
}
System.out.print("Give the number: ");
while(!sc.hasNextInt()) {
sc.next();
}
int choice = sc.nextInt();
sc.nextLine();
try {
Constructor<?> constructor = constructors[choice];
Parameter[] parameters = constructor.getParameters();
Object[] args = new Object[constructor.getParameterCount()];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
System.out.println("Give value of type " + parameter.getType() + " for parameter " + parameter.getName());
args[i] = sc.nextLine();
}
o = constructor.newInstance(args);
System.out.println("New object has been created");
System.out.println(o);
} catch (Exception e) {
System.out.println("Cannot create object " + e);
}
}
void run() {
loop: while(true) {
String action = menu();
switch(action) {
case "q" : break loop;
case "c" : changeClass(); break;
case "p" : printInfo(); break;
case "lf" : listFields(); break;
case "lm" : listMethods(); break;
case "lc" : listConstructors(); break;
case "o" : createObject(); break;
case "oc" : invokeConstructor(); break;
}
}
System.out.println("bye");
}
public static void main(String[] args) {
new PokazRefleksji().run();
}
}
package p24_refleksja;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import p24_refleksja.klasy.ABC;
import p24_refleksja.klasy.Konto;
import p24_refleksja.klasy.Osoba;
public class PrzykladRefleksji {
public static void main(String[] args) throws Exception {
// Różne sposoby uzyskiwania obiektu Class
Class<?> klasa = Osoba.class;
Class<Osoba> klasa1 = Osoba.class;
Osoba osoba = new Osoba();
Class<?> klasa2 = osoba.getClass();
if(klasa2 == klasa1) {
System.out.println("To jest ta sama klasa");
}
try {
Class<?> klasa3 = Class.forName("gotowe.p29_refleksja.klasy.Osoba");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Obiekt klasy: " + klasa);
System.out.println("name: " + klasa.getName());
System.out.println("simpleName: " + klasa.getSimpleName());
System.out.println("nadklasa: " + klasa.getSuperclass().getName());
System.out.println();
System.out.println("Lista konstruktorów");
for (Constructor<?> constructor : klasa.getConstructors()) {
System.out.println(constructor);
}
System.out.println("Tworzę obiekt za pomocą konstr. bezarg.");
Object obiekt1 = klasa.newInstance();
System.out.println("Utworzyłem obiekt: " + obiekt1);
System.out.println("Klasa obiektu: " + obiekt1.getClass());
System.out.println();
System.out.println("Tworzę obiekt za pomocą konstruktora z argumentami");
Constructor<?> constructor3 = klasa.getConstructor(String.class, String.class, int.class);
Object obiekt2 = constructor3.newInstance("Ola", "Nowakowska", 33);
System.out.println("Utworzyłem obiekt: " + obiekt2);
System.out.println("Klasa obiektu: " + obiekt2.getClass());
System.out.println();
System.out.println("Zmienne klasy Osoba:");
for (Field field : klasa.getFields()) {
System.out.println(" + " + field.getName() + " : " +field.getType().getName());
}
System.out.println("Zmienne zadeklarowane w Osoba:");
for (Field field : klasa.getDeclaredFields()) {
System.out.println(" + " + field.getName() + " : " +field.getType().getName());
}
System.out.println("Metody klasy Osoba:");
for (Method field : klasa.getMethods()) {
System.out.println(" * " + field.getName());
}
System.out.println("Metody zadeklarowane w klasie Osoba:");
for (Method field : klasa.getDeclaredMethods()) {
System.out.println(" # " + field.getName());
}
System.out.println();
Field poleImie = klasa.getField("imie");
// System.out.println(poleImie);
poleImie.set(obiekt1, "Ala");
Field poleNazwisko = klasa.getField("nazwisko");
poleNazwisko.set(obiekt1, "Kowalska");
Field poleWiek = klasa.getField("wiek");
poleWiek.setInt(obiekt1, 44);
System.out.println("Ustawiłem pola, teraz obiekt wypisuje się jako:");
System.out.println(obiekt1);
System.out.println("nazwisko = " + poleNazwisko.get(obiekt1));
System.out.println();
for (Field field : klasa.getDeclaredFields()) {
if("haslo".equals(field.getName())) {
try {
field.set(obiekt1, "abc123");
System.out.println("Ustawiłem hasło " + field.get(obiekt1));
} catch(Exception e) {
System.out.println("Nie udało się ustawić prywatnego hasła po raz pierwszy");
System.out.println(e);
}
try {
System.out.println("Próbuję uzyskać dostęp za pomocą setAccessible");
field.setAccessible(true); // lub trySetAccessible() bez ryzyka wyjątku
field.set(obiekt1, "cba321");
System.out.println("Ustawiłem hasło " + field.get(obiekt1));
} catch(Exception e) {
System.out.println("Nie udało się ustawić prywatnego hasła po raz drugi");
System.out.println(e);
}
}
}
System.out.println();
System.out.println("Wywołam metodę:");
Method metodaPrzedstaw = klasa.getMethod("przedstawSie");
metodaPrzedstaw.invoke(obiekt1);
System.out.println();
// Poniżej widać co daje typ generyczny w Class i Constructor
// Dzięki niemu newInstance zwraca obiekt Konto bez żadnego rzutowania
System.out.println("Teraz utworzę obiekt klasy Konto");
Class<Konto> klasaKonto = Konto.class;
Constructor<Konto> constructorKonto = klasaKonto.getConstructor(int.class, int.class, Osoba.class);
Konto konto = constructorKonto.newInstance(123, 1000, obiekt1);
System.out.println(konto);
// mógłbym wywołać metodę w zwykły sposób:
konto.wplata(100);
// ale zobaczmy też jak wywołuje się metodę z parametrami przez API refleksji:
System.out.println("Teraz wywołam metodę wplata");
Method metodaWplata = klasaKonto.getMethod("wplata", int.class);
System.out.println(metodaWplata);
metodaWplata.invoke(konto, 300);
System.out.println(konto);
System.out.println();
Method metodaGetSaldo = klasaKonto.getMethod("getSaldo");
System.out.println(metodaGetSaldo);
Object wynik = metodaGetSaldo.invoke(konto);
System.out.println("getSaldo zwróciło w wyniku: " + wynik.getClass() + " " + wynik);
System.out.println();
System.out.println("A teraz przegląd informacji z deklaracji w klasie ABC");
Class<ABC> klasaABC = ABC.class;
System.out.println("Zadeklarowane pola:");
for (Field field : klasaABC.getDeclaredFields()) {
System.out.println(" * " + field);
System.out.println(" nazwa: " + field.getName());
System.out.println(" typ: " + field.getType());
if(field.getType().getDeclaringClass() != null) {
System.out.println(" Typ zadeklarowany wewnątrz: " + field.getType().getDeclaringClass());
}
Type genericType = field.getGenericType();
// wynikiem jest ParameterizedType tylko jeśli typ jest faktycznie sparametryzowany
if(genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
System.out.println(" To jest typ generyczny " + genericType);
System.out.println(" Parametry typowe:");
for (Type type : parameterizedType.getActualTypeArguments()) {
System.out.println(" > " + type);
}
}
Annotation[] adnotacje = field.getDeclaredAnnotations();
if(adnotacje != null && adnotacje.length > 0) {
System.out.println(" Adnotacje:");
for(Annotation an : adnotacje) {
System.out.println(" " + an);
Class<? extends Annotation> annoType = an.annotationType();
System.out.println(" parametry adnotacji:");
for (Method annoMethod : annoType.getDeclaredMethods()) {
System.out.println(" / " + annoMethod.getName() + " = " + annoMethod.invoke(an));
}
}
}
System.out.println();
}
}
}
package p24_refleksja.klasy;
import java.util.List;
import java.util.Map;
public class ABC {
int i;
String s;
List<String> lista;
Map.Entry<String, Osoba> entry;
@SuppressWarnings("all")
String element;
@Deprecated
public String metoda(String arg) {
return "Hello " + arg;
}
}
package p24_refleksja.klasy;
public class BrakSrodkow extends Exception {
public BrakSrodkow() {
super();
}
public BrakSrodkow(String message) {
super(message);
}
}
package p24_refleksja.klasy;
public class Konto {
// final oznacza, że pole numer jest ustawiane w tworzonym obiekcie, a później się nie zmienia
private final int numer;
private int saldo;
private Osoba wlasciciel;
public Konto(int numer, int saldo, Osoba wlasciciel) {
if(saldo < 0) {
throw new IllegalArgumentException("saldo nie może być ujemne");
}
if(wlasciciel == null) {
throw new IllegalArgumentException("właściciel konta nie może być null");
}
this.numer = numer;
this.saldo = saldo;
this.wlasciciel = wlasciciel;
}
// "encapsulation" - "hermetyzacja"
// Tworząc klasę ukrywamy pola tej klasy jako prywatne
// i dajemy dostęp tylko w takim zakresie, jak chcemy.
// Tutaj: odczyt wszystkich pól,
// ale nie dajemy setterów do:
// - numeru - bo "numer nigdy się nie zmienia"
// - saldo - bo o zmianie salda decydują operacje biznesowe wykonywane na koncie (wplata/wyplata/przelew)
public Osoba getWlasciciel() {
return wlasciciel;
}
// Dzięki enkapsujacji mogę też pilnować, aby na zmiennych były wpisane poprawne wartości
// Np.: nie dopuszczamy wlaściciela null
// Dzięki wyjątkom mogę nie dopuścić do wykonania operacji, która zepsułaby wartość zmiennej w obiekcie
public void setWlasciciel(Osoba wlasciciel) {
if(wlasciciel == null) {
throw new IllegalArgumentException("właściciel konta nie może być null");
}
this.wlasciciel = wlasciciel;
}
public int getNumer() {
return numer;
}
public int getSaldo() {
return saldo;
}
public void wplata(int kwota) {
if(kwota < 0) {
throw new IllegalArgumentException("Ujemna kwota " + kwota + " we wpłacie");
}
saldo += kwota;
}
public void wyplata(int kwota) throws BrakSrodkow {
if(kwota < 0) {
throw new IllegalArgumentException("Ujemna kwota " + kwota + " w wypłacie");
}
if(kwota > saldo) {
throw new BrakSrodkow("Brak środków na koncie nr " + numer);
}
saldo -= kwota;
}
public void przelew(int kwota, Konto kontoDocelowe) throws BrakSrodkow {
if(kwota < 0) {
throw new IllegalArgumentException("Ujemna kwota " + kwota + " w wypłacie");
}
if(kwota > this.saldo) {
throw new BrakSrodkow("Brak środków na koncie nr " + numer);
}
this.saldo -= kwota;
kontoDocelowe.saldo += kwota;
// Obiekt ma dostęp do zmiennych prywatnych innych obiektów tej samej klasy
}
public String toString() {
return "Konto nr " + numer + ", saldo: " + saldo + ", wł.: " + wlasciciel;
}
}
package p24_refleksja.klasy;
public class Osoba {
public String imie, nazwisko;
public int wiek;
private String haslo;
public Osoba() {
}
public Osoba(String imie, String nazwisko, int wiek) {
this.imie = imie;
this.nazwisko = nazwisko;
this.wiek = wiek;
}
public void przedstawSie() {
System.out.println("Nazywam się " + imie + " " + nazwisko + " i mam " + wiek + " lat.");
}
public String toString() {
return imie + " " + nazwisko + " (" + wiek + " lat)";
}
private void metodaPrywatna() {
}
}
package p24_refleksja.sklep_model;
import java.util.List;
public class Customer extends WspolnaNadklasa {
private static final long serialVersionUID = 1L;
private String customerEmail;
private String address;
private String city;
private String customerName;
private String phoneNumber;
private String postalCode;
private List<Order> orders;
public Customer() {
}
public String getCustomerEmail() {
return this.customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCustomerName() {
return this.customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPostalCode() {
return this.postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public List<Order> getOrders() {
return this.orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public Order addOrder(Order order) {
getOrders().add(order);
order.setCustomer(this);
return order;
}
public Order removeOrder(Order order) {
getOrders().remove(order);
order.setCustomer(null);
return order;
}
}
\ No newline at end of file
package p24_refleksja.sklep_model;
import java.util.Date;
import java.sql.Timestamp;
import java.util.List;
public class Order extends WspolnaNadklasa {
private static final long serialVersionUID = 1L;
private Integer orderId;
private Date deliveryDate;
private Timestamp orderDate;
private String status;
private List<OrderProduct> orderProducts;
private Customer customer;
public Order() {
}
public Integer getOrderId() {
return this.orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public Date getDeliveryDate() {
return this.deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public Timestamp getOrderDate() {
return this.orderDate;
}
public void setOrderDate(Timestamp orderDate) {
this.orderDate = orderDate;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public List<OrderProduct> getOrderProducts() {
return this.orderProducts;
}
public void setOrderProducts(List<OrderProduct> orderProducts) {
this.orderProducts = orderProducts;
}
public OrderProduct addOrderProduct(OrderProduct orderProduct) {
getOrderProducts().add(orderProduct);
orderProduct.setOrder(this);
return orderProduct;
}
public OrderProduct removeOrderProduct(OrderProduct orderProduct) {
getOrderProducts().remove(orderProduct);
orderProduct.setOrder(null);
return orderProduct;
}
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
\ No newline at end of file
package p24_refleksja.sklep_model;
import java.math.BigDecimal;
public class OrderProduct extends WspolnaNadklasa {
private static final long serialVersionUID = 1L;
private BigDecimal actualPrice;
private BigDecimal actualVat;
private Integer quantity;
private Order order;
private Product product;
public OrderProduct() {
}
public BigDecimal getActualPrice() {
return this.actualPrice;
}
public void setActualPrice(BigDecimal actualPrice) {
this.actualPrice = actualPrice;
}
public BigDecimal getActualVat() {
return this.actualVat;
}
public void setActualVat(BigDecimal actualVat) {
this.actualVat = actualVat;
}
public Integer getQuantity() {
return this.quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Order getOrder() {
return this.order;
}
public void setOrder(Order order) {
this.order = order;
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
}
\ No newline at end of file
package p24_refleksja.sklep_model;
import java.math.BigDecimal;
public class Product extends WspolnaNadklasa {
private Integer productId;
private String description;
private BigDecimal price;
private String productName;
private BigDecimal vat;
public Product() {
}
public Integer getProductId() {
return this.productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public BigDecimal getVat() {
return this.vat;
}
public void setVat(BigDecimal vat) {
this.vat = vat;
}
}
\ No newline at end of file
package p24_refleksja.sklep_model;
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
Product product = new Product();
product.setProductId(123);
product.setProductName("pralka");
product.setDescription("Pralka bardzo dobrze pierze.");
product.setPrice(new BigDecimal("1390.90"));
product.setVat(new BigDecimal("0.23"));
System.out.println(product);
}
}
package p24_refleksja.sklep_model;
import java.lang.reflect.Field;
// Przykład uniwersalnej implementacji toString, która wypisuje wszystkie dostępne pola obiektu.
abstract class WspolnaNadklasa {
@Override
public String toString() {
StringBuilder result = new StringBuilder();
Class<? extends WspolnaNadklasa> klasa = this.getClass();
result.append(klasa.getSimpleName()).append(" [");
int fieldNo = 0;
for(Field field: klasa.getDeclaredFields())
try {
if(fieldNo++ > 0) {
result.append(", ");
}
Object value;
if(field.trySetAccessible()) {
value = field.get(this);
} else {
value = "!";
}
result.append(field.getName()).append('=').append(value);
} catch(IllegalArgumentException | IllegalAccessException e) {
System.err.println(e);
}
result.append("]");
return result.toString();
}
}
......@@ -35,7 +35,7 @@ public class OpakowywanieSync {
List<String> synchronizowana2 = Collections.synchronizedList(new ArrayList<>());
// Jeśli wątek wykonuje kilka operacji pod rząd, to są one synchronizowane KAŻDA OSOBNO
// Przykład błedu:
// Przykład błędu:
// Jeśli wiele wątków będzie wykonywać taki kod, to dwa wątki mogą usuwać element z jednoelementowej listy -> błąd
if(synchronizowana.size() > 0) {
// tutaj może coś zrobić inny wątek
......
......@@ -13,7 +13,7 @@ class Przeploty {
System.out.println(konto);
Thread wplacacz = new Thread(() -> {
for(int i = 0 ; i < N; i++) {
for(int i = 0; i < N; i++) {
konto.wplata(KWOTA);
}
});
......
......@@ -39,7 +39,7 @@ class Konto {
// saldo --; // potrącić prowizję
// wątek obudzony z notify musi jeszcze poczekać, aż ja skończę tu robotę
// bo to jeszcze ja zajmuję sekcje "synchorized"
// bo to jeszcze ja zajmuję sekcje "synchronized"
}
public synchronized void wyplata(int kwota) throws BrakSrodkow {
......
......@@ -17,6 +17,7 @@ public class Watki1 {
} catch (InterruptedException e) {
}
System.out.println("main: poczekałem sobie");
System.out.println("status wątku w trakcie działania: " + th1.getState());
System.out.println("koniec main");
// main dochodzi do końca, a wątki działają dalej
......
......@@ -17,10 +17,9 @@ public class Watki2_Join {
try {
Thread.sleep(90);
} catch (InterruptedException e) {
}
System.out.println("main: Teraz będę czekał na wątki za pomocą join");
}
System.out.println("stan przed join: " + th1.getState());
System.out.println("main: Teraz będę czekał na wątki za pomocą join");
// wątek main czeka na zakończenie wątków th1, th2, th3
// jeśli one się skończyły wcześniej, to od razu przechodzi dalej
......
package watki.podstawy;
public class Watki2a_JoinBezSleep {
public static void main(String[] args) {
System.out.println("Początek main");
Thread th1 = new Thread(new WatekWypisujacy("A", 200, 0));
Thread th2 = new Thread(new WatekWypisujacy("B", 200, 0));
Thread th3 = new Thread(new WatekWypisujacy("C", 200, 0));
System.out.println("stan przed start: " + th1.getState());
th1.start();
th2.start();
th3.start();
System.out.println("main: wątki uruchomione, mój nr " + Thread.currentThread().getId());
System.out.println("stan przed join: " + th1.getState());
// wątek main czeka na zakończenie wątków th1, th2, th3
// jeśli one się skończyły wcześniej, to od razu przechodzi dalej
try {
th1.join();
th2.join();
th3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main: doczekałem się na zakończenie wątków");
System.out.println("stan po join: " + th1.getState());
System.out.println("koniec main");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment