Commit 5eec33ba by Patryk Czarnik

zmiana nazwy pakietu kolekcje

parent 0263eccd
package p15_wrappery;
import java.util.concurrent.atomic.AtomicInteger;
public class Parametry {
static void test(int i, Integer j, AtomicInteger k) {
i += 5;
j += 6; // to nie zmienia wartości wewnątrz obiektu, tylko tworzy nowy obiekt
// tak jakby: j = new Integer(j.intValue() + 6);
k.addAndGet(7);
System.out.println("i: " + i + " , j: " + j + " , k: " + k);
}
public static void main(String[] args) {
int x = 100;
Integer y = 200;
// Integer y = new Integer(200); // zadziała tak samo
AtomicInteger z = new AtomicInteger(300);
System.out.println("x: " + x + " , y: " + y + " , z: " + z);
test(x, y, z);
System.out.println("x: " + x + " , y: " + y + " , z: " + z);
}
}
package p15_wrappery;
public class Wrappery1_Podstawy {
public static void main(String[] args) {
// Dla każdego z 8 typów prostych istnieje odpowiadająca mu klasa ("opakowaniowa"?), tzw. "wrapper".
// Obiekt klasy wrapper zawiera w sobie wartość danego typu.
// Wszystkie klasy wrapperów są NIEMUTOWALNE, tzn. wartość w obiekcie nigdy nie ulega zmianie; /na zmienną typu wrapper można wpisać nowy obiekt, ale to nie to samo./
int i = 103;
// Obiekt klasy opakowaniowej na podstawie wartości można utworzyć:
// - za pomocą konstruktora (obecnie niezalecane)
Integer ii1 = new Integer(i);
// - za pomocą metody valueOf
Integer ii2 = Integer.valueOf(i);
// - za pomocą automatycznej konwersji (autoboxing, od Javy 5); wewnętrznie jest to realizowane za pomocą valueOf
Integer ii3 = i;
byte y = 15;
Byte yy1 = new Byte(y);
Byte yy2 = Byte.valueOf(y);
Byte yy3 = y;
short s = 10_000;
Short ss1 = new Short(s);
Short ss2 = Short.valueOf(s);
Short ss3 = s;
long l = 4_000_000L;
Long ll1 = new Long(l);
Long ll2 = Long.valueOf(l);
Long ll3 = l;
float f = 3.14F;
Float ff1 = new Float(f);
Float ff2 = Float.valueOf(f);
Float ff3 = f;
double d = 1.4142;
Double dd1 = new Double(d);
Double dd2 = Double.valueOf(d);
Double dd3 = d;
char c = 'A';
Character cc1 = new Character(c);
Character cc2 = Character.valueOf(c);
Character cc3 = c;
boolean b = true;
Boolean bb1 = new Boolean(b);
Boolean bb2 = Boolean.valueOf(b);
Boolean bb3 = b;
// Dodatkowo istnieje klasa Void, odpowiadająca typowi void.
// Nie da się utworzyć obiektu tej klasy.
Void v = null;
}
}
package p15_wrappery;
import java.util.ArrayList;
import java.util.List;
public class Wrappery2_Zastosowania {
public static void main(String[] args) {
// Zastosowania wrapperów.
// 1) Stałe i metody statyczne zdefiniowane w klasie
String liczbaTekstowo = "12345";
int liczba = Integer.parseInt(liczbaTekstowo);
Integer obiekt = Integer.valueOf(liczbaTekstowo);
System.out.println(liczba * 2);
System.out.printf("Typ %s ma %d bajty, czyli %d bity, minimalna wartość to %d, a maksymalna %d\n",
Integer.TYPE.getSimpleName(), Integer.BYTES, Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE);
// 2) Obiekt jako "wartość opcjonalna".
// Zmienna/funkcja typu int MUSI mieć/zwracać jakąś wartość. Każdy ciąg bitów w zmiennej typu prostego oznacza jakąś konkretną wartość.
// Zmienna typu obiektowego może wskazywać na obiekt LUB mieć wartość null. null może być traktowany jako dodatkowa wartość oznaczająca brak danych/brak wyniku
// Współcześnie bardziej zalecane do tego celu jest używanie klas Optional (np. OptionalInt), ale tradycyjnie używało się wrapperów i w wielu miejscach to pozostało.
int[] a = {13, 7, 14, 3, 12};
int[] b = {13, 7, 3, 9, -5};
Integer wynik1 = pierwszaParzysta(a);
if(wynik1 != null) {
System.out.println("pierwszy wynik: " + wynik1);
} else {
System.out.println("brak pierwszego wyniku");
}
Integer wynik2 = pierwszaParzysta(b);
if(wynik2 != null) {
System.out.println("drugi wynik: " + wynik2);
} else {
System.out.println("brak drugiego wyniku");
}
// 3) Kolekcje i bardziej ogólnie deklaracje typów generycznych.
// nie da rady: List<int> listaLiczb1 = new ArrayList<>();
List<Integer> listaLiczb = new ArrayList<>();
for(int x : a) {
listaLiczb.add(x);
}
System.out.println(listaLiczb);
}
public static Integer pierwszaParzysta(int[] tab) {
for(int x : tab) {
if(x % 2 == 0) {
return x;
}
}
return null;
}
}
package p15_wrappery;
// Integer i Long są dużo wolniejsze niż int i long
// z tego powodu używanie List<Integer> jest dużo wolniejsze niż int[]
// Gdy w Javie 8 wymyślano Streamy, stworzono osobne wersje IntStream, DoubleStream, LongStream
// i lepiej ich używać zamiast Stream<Integer> itd.
public class Wrappery3_Wydajnosc {
static Long suma1(int n) {
Long wynik = 0L;
for(Integer i = 1; i <= n; i++) {
wynik += i;
}
return wynik;
}
static long suma2(int n) {
long wynik = 0L;
for(int i = 1; i <= n; i++) {
wynik += i;
}
return wynik;
}
public static void main(String[] args) {
int n = 1_000_000_000;
long p, k;
System.out.println("v1 start");
p = System.currentTimeMillis();
Long wynik1 = suma1(n);
k = System.currentTimeMillis();
System.out.println("v1 wynik: " + wynik1);
System.out.println("czas: " + (k - p));
System.out.println();
System.out.println("v2 start");
p = System.currentTimeMillis();
long wynik2 = suma2(n);
k = System.currentTimeMillis();
System.out.println("v2 wynik: " + wynik2);
System.out.println("czas: " + (k - p));
}
}
package p15_wrappery;
public class Wrappery4_WielkaCiekawostka {
public static void main(String[] args) {
Integer x, y;
x = 100;
y = 100;
System.out.println(x == y);
x = 200;
y = 200;
System.out.println(x == y);
System.out.println();
// wyjasnienie: automatyczny boxing jest robiony za pomocą valueOf:
x = Integer.valueOf(100);
y = Integer.valueOf(100);
System.out.println(x == y);
System.out.println(x.equals(y));
System.out.println();
x = Integer.valueOf(200);
y = Integer.valueOf(200);
System.out.println(x == y);
System.out.println(x.equals(y));
}
}
package p15_wrappery;
import java.util.HashMap;
import java.util.Map;
public class Wrappery5_Null {
static int pomnoz(Integer a) {
return 2*a;
}
static int dodaj(int a) {
return 2*a;
}
public static void main(String[] args) {
Integer x, y;
x = 55;
y = null;
System.out.println(pomnoz(x));
System.out.println(pomnoz(y)); // NPE w środku metody
System.out.println(dodaj(x));
System.out.println(dodaj(y)); // NPE przy przekazywaniu parametru
int z = y; // NPE przy przypisaniu
System.out.println(z);
// bo tak naprawde
int z2 = y.intValue();
// Szczególnie trzeba uważać przy korzystaniu z map:
Map<String, Integer> mapa = new HashMap<>();
mapa.put("Ala", 30);
mapa.put("Ola", 40);
// typy błąd programisty:
// NullPointerException, bo mapa.get zwraca null, a my wpisujemy to na zmienną int
// int wiek = mapa.get("Ula");
// System.out.println(wiek);
Integer wiek2 = mapa.get("Ula");
System.out.println(wiek2);
// teraz operacje liczbowe będą powodowały błedy:
// System.out.println(wiek2 + 1);
}
}
package p15_wrappery;
public class Wrappery6_Number {
public static void main(String[] args) {
Number n = 777;
System.out.println(n.byteValue());
System.out.println(n.shortValue());
System.out.println(n.intValue());
System.out.println(n.longValue());
System.out.println(n.floatValue());
System.out.println(n.doubleValue());
}
}
package p15_wrappery;
public class Wrappery7_Parsowanie {
public static void main(String[] args) {
String tekst = "1234";
// typ wyniku int
int x = Integer.parseInt(tekst);
System.out.println(2*x);
// typ wyniku Integer
Integer y = Integer.valueOf(tekst);
// skompiluje się też, ale mnie wydajne:
int xx = Integer.valueOf(tekst);
Integer yy = Integer.parseInt(tekst);
double d = Double.parseDouble(tekst);
System.out.println(d);
}
}
package p15_wrappery;
import java.util.ArrayList;
import java.util.List;
public class Wrappery8_Lista {
public static void main(String[] args) {
List<String> napisy = new ArrayList<>();
napisy.add("Ala");
napisy.add("Ola");
napisy.add("Ela");
napisy.add("Ula");
System.out.println(napisy);
napisy.remove(2); // usuwa według indeksu, zwraca referencję do usuwanego obiektu
System.out.println(napisy);
napisy.remove("Ala"); // usuwa wg wartości, zwraca boolean mówiący czy element został usunięty
System.out.println(napisy);
System.out.println();
List<Integer> liczby = new ArrayList<>();
liczby.add(4);
liczby.add(8);
liczby.add(1);
liczby.add(5);
liczby.add(13);
liczby.add(12);
liczby.add(5);
liczby.add(1);
System.out.println(liczby);
// liczby.remove(12); // traktowane jako pozycja
Integer co = liczby.remove(0); // traktowane jako pozycja
// System.out.println(liczby);
// traktowane jako obiekt - czyli wartość wpisu
boolean czy = liczby.remove((Object)13);
liczby.remove(new Integer(12));
liczby.remove(Integer.valueOf(5));
System.out.println(liczby);
}
}
package p15_wrappery;
import java.util.ArrayList;
import java.util.Locale;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class Wrappery9_WydajnoscList {
// wiekość tablicy
private static final int N = 100_000_000;
// ilość powtórzeń odczytu
private static final int K = 20;
private static void zmierzCzas(String tytul, Runnable procedura) {
System.out.println("\nZaczynam " + tytul);
long start = System.nanoTime();
procedura.run();
long koniec = System.nanoTime();
double czas = (koniec - start) * 1e-9;
System.out.printf(Locale.US, "%s: %10.6f s\n", tytul, czas);
}
private static void wyczysc() {
try {
System.gc();
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
private static void petla() {
long suma = 0L;
for(int k = 0; k < K; k++) {
for(int i = 0; i < N; i++) {
suma += i;
}
}
System.out.println(suma);
}
private static void tablica() {
int[] t = new int[N];
for(int i = 0; i < N; i++) {
t[i] = i;
}
long suma = 0L;
for(int k = 0; k < K; k++) {
for(int x : t) {
suma += x;
}
}
System.out.println(suma);
}
private static void array_list() {
ArrayList<Integer> l = new ArrayList<>();
for(int i = 0; i < N; i++) {
l.add(i);
}
long suma = 0L;
for(int k = 0; k < K; k++) {
for(int x : l) {
suma += x;
}
}
System.out.println(suma);
}
private static void stream_range() {
long suma = 0L;
for(int k = 0; k < K; k++) {
suma += LongStream.range(0, N).sum();
}
System.out.println(suma);
}
private static void stream_tablica() {
int[] t = IntStream.range(0, N).toArray();
long suma = 0L;
for(int k = 0; k < K; k++) {
suma += IntStream.of(t).asLongStream().sum();
}
System.out.println(suma);
}
public static void main(String[] args) {
System.out.println("Startujemy...");
zmierzCzas("Pętla bez kolekcji", Wrappery9_WydajnoscList::petla);
wyczysc();
zmierzCzas("Tablica", Wrappery9_WydajnoscList::tablica);
wyczysc();
zmierzCzas("ArrayList", Wrappery9_WydajnoscList::array_list);
wyczysc();
zmierzCzas("Stream (range)", Wrappery9_WydajnoscList::stream_range);
wyczysc();
zmierzCzas("Stream (tablica)", Wrappery9_WydajnoscList::stream_tablica);
wyczysc();
System.out.println("Koniec");
}
}
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