Commit 2c1b00b1 by Patryk Czarnik

Gotowe przykłady różne

parent a94eff9b
package p35_daty;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoField;
public class DataICzas {
public static void main(String[] args) {
// Która godzina jest w innej strefie czasowej
LocalDateTime dt2 = LocalDateTime.now(ZoneId.of("UTC-4"));
System.out.println(dt2);
LocalDateTime dt = LocalDateTime.now();
System.out.println(dt);
// Metody "with" modyfikują wybrane pole i zwracają wmieniony obiekt
dt.with(ChronoField.HOUR_OF_DAY, 17);
System.out.println(dt); // nie widać zmiany, bo dato-czasy są immutable
// przypisanie na zmienną dt zapisuje zmieniony obiekt
dt = dt.with(ChronoField.HOUR_OF_DAY, 17);
System.out.println(dt);
dt = dt.withDayOfMonth(13);
System.out.println(dt);
dt = dt.withDayOfYear(200);
System.out.println(dt);
dt = dt.with(ChronoField.SECOND_OF_DAY, 12360);
System.out.println(dt);
try {
dt = dt.with(ChronoField.OFFSET_SECONDS, 7200);
System.out.println(dt);
} catch (Exception e) {
System.out.println("Był wyjątek " + e.getClass() + " " + e.getMessage());
}
dt = LocalDateTime.now();
System.out.println(dt);
OffsetDateTime przesuniety = dt.atOffset(ZoneOffset.ofHours(5));
System.out.println(przesuniety);
dt = LocalDateTime.parse("2019-05-08T14:55:04.360");
System.out.println(dt);
dt = LocalDateTime.parse("2019-05-08T14:55");
System.out.println(dt);
dt = LocalDateTime.parse("2019-05-08T14:55:00");
System.out.println(dt); // sekundy równe zero w ogóle się nie wypisują
}
}
package p35_daty;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Formatowanie1_Standardy {
public static void main(String[] args) {
LocalDateTime teraz = LocalDateTime.now();
DateTimeFormatter[] formats = {
DateTimeFormatter.BASIC_ISO_DATE,
DateTimeFormatter.ISO_DATE,
DateTimeFormatter.ISO_DATE_TIME,
DateTimeFormatter.ISO_LOCAL_DATE_TIME,
DateTimeFormatter.ISO_ORDINAL_DATE,
DateTimeFormatter.ISO_WEEK_DATE,
};
System.out.println("Format domyslny:");
System.out.println(teraz.toString());
System.out.println(LocalDate.now().toString());
System.out.println(LocalTime.now().toString());
System.out.println();
for (DateTimeFormatter df : formats) {
// formatowanie można wywoływać na dwa sposoby
System.out.println(teraz.format(df));
System.out.println(df.format(teraz));
}
}
}
package p35_daty;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Formatowanie2_Jezykowo {
public static void main(String[] args) {
ZonedDateTime teraz = ZonedDateTime.now();
DateTimeFormatter df = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.FULL)
.withLocale(new Locale("ru", "RU"));
System.out.println(teraz.format(df));
}
}
package p35_daty;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Formatowanie3_Jezykowo_BezStrefy {
public static void main(String[] args) {
LocalDateTime teraz = LocalDateTime.now();
Locale[] locales = {
new Locale("pl", "PL"),
new Locale("pl"),
new Locale("fr", "FR"),
new Locale("de", "DE"),
new Locale("es", "ES"),
new Locale("it", "IT"),
new Locale("ru", "RU"),
new Locale("ja", "JP"),
new Locale("ar", "EY"),
new Locale("en", "GB"),
new Locale("en", "US"),
new Locale("en")
};
FormatStyle[] styles = {
//FormatStyle.FULL,
//FormatStyle.LONG,
FormatStyle.MEDIUM,
FormatStyle.SHORT
};
for(Locale locale : locales) {
System.out.println("\nLOCALE " + locale);
for(FormatStyle style : styles) {
DateTimeFormatter df = DateTimeFormatter.ofLocalizedDateTime(style);
System.out.println(teraz.format(df));
}
}
}
}
package p35_daty;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Formatowanie4_Jezykowo_Strefa {
public static void main(String[] args) {
ZonedDateTime teraz = ZonedDateTime.now();
Locale[] locales = {
new Locale("pl", "PL"),
new Locale("pl"),
new Locale("fr", "FR"),
new Locale("de", "DE"),
new Locale("es", "ES"),
new Locale("it", "IT"),
new Locale("ru", "RU"),
new Locale("ja", "JP"),
new Locale("ar", "EY"),
new Locale("en", "GB"),
new Locale("en", "US"),
new Locale("en")
};
FormatStyle[] styles = {
FormatStyle.FULL,
FormatStyle.LONG,
FormatStyle.MEDIUM,
FormatStyle.SHORT
};
for(Locale locale : locales) {
System.out.println("\nLOCALE " + locale);
for(FormatStyle style : styles) {
DateTimeFormatter df = DateTimeFormatter
.ofLocalizedDateTime(style)
.withLocale(locale);
System.out.println(teraz.format(df));
System.out.println(df.format(teraz));
}
}
}
}
package p35_daty;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Formatowanie5_Pattern {
public static void main(String[] args) {
ZonedDateTime teraz = ZonedDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("YYYY-MM-dd");
System.out.println(teraz.format(df));
df = DateTimeFormatter.ofPattern("dd.MM.YY");
System.out.println(teraz.format(df));
df = DateTimeFormatter.ofPattern("dd.MM.YYY");
System.out.println(teraz.format(df));
df = DateTimeFormatter.ofPattern("d M Y");
System.out.println(teraz.format(df));
df = DateTimeFormatter.ofPattern("dd MM YY");
System.out.println(teraz.format(df));
df = DateTimeFormatter.ofPattern("e dd MMM");
System.out.println(teraz.format(df));
df = DateTimeFormatter.ofPattern("EEE, dd MMMM");
System.out.println(teraz.format(df));
df = DateTimeFormatter.ofPattern("EEEE, dd MMMMM");
System.out.println(teraz.format(df));
}
}
package p35_daty;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Formatowanie6_Parse {
public static void main(String[] args) {
LocalDateTime data = LocalDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("EEEE,yyyyMMdd HH@mm");
System.out.println(data.format(df));
System.out.println(data);
System.out.println();
data = LocalDateTime.parse("wtorek,19981208 12@13", df);
System.out.println(data);
}
}
package p35_daty;
import java.time.LocalDate;
import java.time.Period;
public class Okresy {
public static void main(String[] args) {
LocalDate d1 = LocalDate.parse("2015-05-13");
LocalDate d2 = LocalDate.parse("2016-09-11");
Period p1 = Period.between(d1, d2);
System.out.println(p1);
Period p2 = Period.of(3, 14, 44);
System.out.println(p2);
LocalDate dzisiaj = LocalDate.now();
LocalDate przyszlosc1 = dzisiaj.plus(p2);
System.out.println(przyszlosc1);
LocalDate przyszlosc2 = (LocalDate) p2.addTo(dzisiaj);
System.out.println(przyszlosc2);
Period p3 = p2.normalized();
System.out.println(p3); // miesiące są normalizowane (miesiące powyżej 12 są zamieniane na lata), ale dni nie, bo się nie da
System.out.println();
Period p4 = Period.parse("P3M2W10D"); // tygodnie od razu przeliczają się na dni, ale miesiące nie przeliczają się na lata
System.out.println(p4);
Period p5 = Period.ofWeeks(3);
System.out.println(p5);
Period p6 = Period.ofDays(50);
System.out.println(p6);
}
}
package p35_daty;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
public class Porownywanie {
public static void main(String[] args) {
LocalDate d1 = LocalDate.now();
LocalDate d2 = LocalDate.of(2016, 12, 7);
LocalDate d3 = LocalDate.parse("2016-04-04");
System.out.println(d1.equals(d2)); // T
System.out.println(d1.equals(d3)); // F
if(d1.compareTo(d3) > 0) {
System.out.println("d1 później niż d3");
} else {
System.out.println("d1 wcześniej niż d3");
}
if(d1.isAfter(d3)) {
System.out.println("d1 później niż d3");
} else {
System.out.println("d1 wcześniej niż d3");
}
ArrayList<LocalDate> daty = new ArrayList<>();
daty.add(LocalDate.of(2015, 12, 24));
daty.add(LocalDate.of(2016, 9, 24));
daty.add(LocalDate.of(2015, 3, 11));
daty.add(LocalDate.of(2016, 8, 8));
System.out.println(daty);
Collections.sort(daty);
System.out.println(daty);
}
}
package p35_daty;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
public class ProsteDaty {
public static void main(String[] args) {
LocalDate data1 = LocalDate.now();
System.out.println(data1);
LocalDate data2 = LocalDate.of(2016, 12, 5);
System.out.println(data2);
LocalDate data3 = LocalDate.of(2016, Month.DECEMBER, 5);
System.out.println(data3);
LocalDate data4 = LocalDate.parse("2016-12-05");
System.out.println(data4);
LocalDate data5 = LocalDate.parse("2016-02-29");
System.out.println(data5);
// LocalDate data6 = LocalDate.parse("2015-02-29");
// System.out.println(data6);
// najpierw starsza potem pozniejsza
Period czasTrwania = Period.between(data4, data1);
System.out.println(czasTrwania);
System.out.println(czasTrwania.getDays());
}
}
package p35_daty;
import java.time.LocalTime;
public class ProstyCzas {
public static void main(String[] args) {
LocalTime czas1 = LocalTime.now(); // ustawia z dokladnoscia do milisekundy
System.out.println(czas1);
// uwaga: można utworzyć czas nie podając sekund
LocalTime czas2 = LocalTime.of(12, 15);
System.out.println(czas2);
LocalTime czas3 = LocalTime.of(12, 15, 33);
System.out.println(czas3);
// uwaga: nanosekumdy podajemy jako liczbę całkowitą (int)
LocalTime czas4 = LocalTime.of(12, 15, 33, 333222111);
System.out.println(czas4);
// to oznacza jedną nanosekundę (miliardową część sekundy),
// a nie jedną dizesiątą sekundy
LocalTime czas5 = LocalTime.of(12, 15, 33, 1);
System.out.println(czas5);
}
}
package p35_daty;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class PrzykladInstant {
public static void main(String[] args) {
Instant czas = Instant.now();
System.out.println(czas);
ZonedDateTime uNas = czas.atZone(ZoneId.systemDefault());
System.out.println(uNas);
ZonedDateTime zoned = ZonedDateTime.now();
System.out.println(zoned);
}
}
package p35_daty;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class StareFormatowanieDat {
public static void display(Date date, Locale locale) {
DateFormat df;
df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
System.out.println("Date DEFAULT: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.FULL, locale);
System.out.println("Date FULL: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.LONG, locale);
System.out.println("Date LONG: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
System.out.println("Date MEDIUM: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
System.out.println("Date SHORT: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
System.out.println("Time DEFAULT: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.FULL, locale);
System.out.println("Time FULL: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.LONG, locale);
System.out.println("Time LONG: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
System.out.println("Time MEDIUM: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
System.out.println("Time SHORT: " + df.format(date));
//Tu już tylko przykładowo
df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
System.out.println("DateTime DEFAULT DEFAULT: " + df.format(date));
df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, locale);
System.out.println("DateTime LONG SHORT: " + df.format(date));
}
public static void main(String[] args) {
Locale[] all = {
new Locale("pl", "PL"),
new Locale("pl"),
new Locale("de", "DE"),
new Locale("fr", "FR"),
new Locale("ru", "RU"),
new Locale("es", "ES"),
new Locale("it", "IT"),
new Locale("ja", "JP"),
new Locale("ar", "EY"),
new Locale("en", "GB"),
new Locale("en", "US"),
new Locale("en") };
Date now = Calendar.getInstance().getTime();
DateFormat df = DateFormat.getInstance();
System.out.println("domyślnie: " + df.format(now));
for (Locale locale : all) {
System.out.println("Dla locali " + locale.toString());
display(now, locale);
System.out.println();
}
}
}
package p35_daty;
import java.text.DateFormat;
import java.util.Locale;
import java.util.Locale.Category;
public class WypiszDostepneLocale {
public static void main(String[] args) {
System.out.println("DEFAULT: "+Locale.getDefault());
System.out.println("DISPLAY: "+Locale.getDefault(Category.DISPLAY));
System.out.println("FORMAT: "+Locale.getDefault(Category.FORMAT));
for (Locale loc : DateFormat.getAvailableLocales()) {
System.out.println(loc.toString() + " " + loc.getDisplayLanguage() + "/" + loc.getDisplayCountry() );
}
}
}
package p36_lokalizacja;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
public class EnumerateBundle {
public static void main(String[] args) {
Locale actualLocale;
if (args.length == 2) {
String language = args[0];
String country = args[1];
actualLocale = new Locale(language, country);
} else {
actualLocale = Locale.getDefault();
}
ResourceBundle messages = ResourceBundle.getBundle("pakiet.NaszBundle", actualLocale);
Enumeration<String> bundleKeys = messages.getKeys();
while (bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = messages.getString(key);
System.out.println("key = " + key + ", " + "value = " + value);
}
}
}
package p36_lokalizacja;
public class HelloFixed {
public static void main(String[] args) {
System.out.println("Hello.");
System.out.println("How are you?");
System.out.println("Goodbye.");
}
}
package p36_lokalizacja;
import java.util.Arrays;
import java.util.Locale;
import java.util.ResourceBundle;
public class HelloInternational {
public static void main(String[] args) {
Locale actualLocale;
if (args.length == 2) {
String language = args[0];
String country = args[1];
actualLocale = new Locale(language, country);
} else {
actualLocale = Locale.getDefault();
}
System.out.println("Używam locali "+actualLocale);
ResourceBundle messages = ResourceBundle.getBundle("tlumaczenia.NaszBundle", actualLocale);
System.out.println("Klasa bundla "+messages.getClass().getName());
System.out.println(messages.getString("greetings"));
System.out.println(messages.getObject("inquiry"));
System.out.println(messages.getString("farewell"));
Object obiekt = messages.getObject("liczba");
// Object obiekt = messages.getString("liczba"); // wyjatek
System.out.println("Klasa "+obiekt.getClass() + " " + obiekt);
System.out.println(Arrays.toString(messages.getStringArray("tablica")));
}
}
package p36_lokalizacja;
import java.text.DateFormat;
import java.util.Locale;
import java.util.Locale.Category;
public class PrintAvailableLocale {
public static void main(String[] args) {
System.out.println("DEFAULT: "+Locale.getDefault());
System.out.println("DISPLAY: "+Locale.getDefault(Category.DISPLAY));
System.out.println("FORMAT: "+Locale.getDefault(Category.FORMAT));
for (Locale loc : DateFormat.getAvailableLocales()) {
System.out.println(loc.toString() + " " + loc.getDisplayLanguage() + "/" + loc.getDisplayCountry() );
}
}
}
package p36_lokalizacja;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class SetDefault {
public static void main(String[] args) {
Date now = Calendar.getInstance().getTime();
System.out.println(Locale.getDefault());
DateFormat df1 = DateFormat.getDateInstance(DateFormat.FULL);
System.out.println(df1.format(now));
Locale.setDefault(Locale.CANADA_FRENCH);
System.out.println(Locale.getDefault());
System.out.println("Nowy formatter:");
DateFormat df2 = DateFormat.getDateInstance(DateFormat.FULL);
System.out.println(df2.format(now));
System.out.println("Formatuje starym formatterem:");
System.out.println(df1.format(now));
}
}
package p36_lokalizacja;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Locale.Category;
public class SetDefault2 {
public static void main(String[] args) {
Date now = Calendar.getInstance().getTime();
System.out.println(Locale.getDefault());
DateFormat df1 = DateFormat.getDateInstance(DateFormat.FULL);
System.out.println(df1.format(now));
//Locale.setDefault(Category.FORMAT, Locale.US);
Locale.setDefault(Category.FORMAT, Locale.CANADA_FRENCH);
Locale.setDefault(Category.DISPLAY, Locale.US);
System.out.println(Locale.getDefault());
DateFormat df2 = DateFormat.getDateInstance(DateFormat.FULL);
System.out.println(df2.format(now));
}
}
package p36_lokalizacja;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
// pl_PL en_US
public class UseLocale1 {
public static void main(String[] args) {
Locale polski = new Locale("pl");
Locale brytyjski = new Locale("en", "GB");
Locale amerykański = new Locale("en", "US");
Locale techniczny = new Locale("en", "US", "UTF8");
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
DateFormat dfPL = DateFormat.getDateInstance(DateFormat.FULL, polski);
DateFormat dfGB = DateFormat.getDateInstance(DateFormat.FULL, brytyjski);
DateFormat dfAM = DateFormat.getDateInstance(DateFormat.FULL, amerykański);
Date now = Calendar.getInstance().getTime();
System.out.println(df.format(now));
System.out.println(dfPL.format(now));
System.out.println(dfGB.format(now));
System.out.println(dfAM.format(now));
}
}
package p36_lokalizacja;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class UseLocale2 {
public static void main(String[] args) {
Locale polski = new Locale("pl");
Locale brytyjski = Locale.UK;
Locale amerykański = Locale.US;
DateFormat dfPL = DateFormat.getDateInstance(DateFormat.FULL, polski);
DateFormat dfGB = DateFormat.getDateInstance(DateFormat.FULL, brytyjski);
DateFormat dfAM = DateFormat.getDateInstance(DateFormat.FULL, amerykański);
DateFormat dfJP = DateFormat.getDateInstance(DateFormat.FULL, Locale.JAPAN);
Date now = Calendar.getInstance().getTime();
System.out.println(dfPL.format(now));
System.out.println(dfGB.format(now));
System.out.println(dfAM.format(now));
System.out.println(dfJP.format(now));
System.out.println(Locale.JAPAN);
}
}
package p36_lokalizacja;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class UseLocale3_Builder {
public static void main(String[] args) {
Locale polski1 = new Locale.Builder().setLanguage("pl").build();
Locale.Builder builder = new Locale.Builder();
builder.setLanguage("pl");
Locale polski = builder.build();
builder.clear();
builder.setLanguage("ru").setRegion("RU").setScript("Cyrl");
Locale rosyjski = builder.build();
DateFormat dfPL = DateFormat.getDateInstance(DateFormat.FULL, polski);
DateFormat dfRU = DateFormat.getDateInstance(DateFormat.FULL, rosyjski);
Date now = Calendar.getInstance().getTime();
System.out.println(dfPL.format(now));
System.out.println(dfRU.format(now));
}
}
package p36_lokalizacja.formatowanie;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsowanieDat {
public static void main(String[] args) {
System.out.println("Wlasne wzorce");
//DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT);
//DateFormat f = new SimpleDateFormat("HH:mm");
DateFormat f = new SimpleDateFormat("HH:mm:ss z");
Date now = new Date();
try {
System.out.println("Wypisuje "+f.format(now));
//Date data = f.parse("15.03.09");
Date data = f.parse("20:12:13 GMT śmieci potem");
System.out.println("Wczytana "+data);
} catch (ParseException e) {
System.err.println("Wyjatek 1 "+e.getMessage());
}
}
}
package p36_lokalizacja.formatowanie;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class PredefinedFormats_Date {
public static void display(Date date, Locale locale) {
DateFormat df;
df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
System.out.println("Date DEFAULT: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.FULL, locale);
System.out.println("Date FULL: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.LONG, locale);
System.out.println("Date LONG: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
System.out.println("Date MEDIUM: " + df.format(date));
df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
System.out.println("Date SHORT: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
System.out.println("Time DEFAULT: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.FULL, locale);
System.out.println("Time FULL: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.LONG, locale);
System.out.println("Time LONG: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
System.out.println("Time MEDIUM: " + df.format(date));
df = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
System.out.println("Time SHORT: " + df.format(date));
//Tu już tylko przykładowo
df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
System.out.println("DateTime DEFAULT DEFAULT: " + df.format(date));
df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, locale);
System.out.println("DateTime LONG SHORT: " + df.format(date));
}
public static void main(String[] args) {
Locale[] all = {
new Locale("pl", "PL"),
new Locale("pl"),
new Locale("de", "DE"),
new Locale("fr", "FR"),
new Locale("ru", "RU"),
new Locale("es", "ES"),
new Locale("it", "IT"),
new Locale("ja", "JP"),
new Locale("ar", "EY"),
new Locale("en", "GB"),
new Locale("en", "US"),
new Locale("en") };
Date now = Calendar.getInstance().getTime();
DateFormat df = DateFormat.getInstance();
System.out.println("domyślnie: " + df.format(now));
for (Locale locale : all) {
System.out.println("Dla locali " + locale.toString());
display(now, locale);
System.out.println();
}
}
}
package p36_lokalizacja.formatowanie;
import java.text.NumberFormat;
import java.util.Locale;
public class PredefinedFormats_Number {
public static void displayNumbers(Locale locale) {
Integer i = new Integer(123456);
Double d = new Double(1654.32173645263);
//NumberFormat nf = NumberFormat.getNumberInstance(locale);
NumberFormat nf = NumberFormat.getInstance(locale);
//nf.setMaximumFractionDigits(6);
System.out.println(nf.format(i));
System.out.println(nf.format(d));
}
public static void displayPercent(Locale locale) {
Integer i = new Integer(13);
Double d = new Double(0.7533);
NumberFormat nf = NumberFormat.getPercentInstance(locale);
System.out.println(nf.format(i));
System.out.println(nf.format(d));
}
public static void displayCurrencies(Locale locale) {
Double d = new Double(2200.90);
NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
System.out.println(nf.format(d));
}
public static void main(String[] args) {
Locale[] all = {
new Locale("pl", "PL"),
new Locale("pl"),
new Locale("de", "DE"),
new Locale("fr", "FR"),
new Locale("en", "GB"),
new Locale("en", "US"),
new Locale("en") };
for (Locale locale : all) {
System.out.println("Dla locali " + locale.toString());
displayNumbers(locale);
displayPercent(locale);
displayCurrencies(locale);
System.out.println();
}
}
}
package p36_lokalizacja.formatowanie;
import java.io.File;
import java.util.Locale;
public class Printf {
public static void main(String[] args) {
System.out.println(Locale.getDefault());
int x = 7, y = 13;
double f = 112233.456;
String s = "Ala ma kota";
Object o = new File("plik.txt");
System.out.printf("Dwa inty: %d %d, float: %f %f, stringi: %s %s%n",
x, y, f, Math.PI, s, o);
System.out.printf(new Locale("en", "US"), "Dwa inty: %d %d, float: %f %f, stringi: %s %s%n",
x, y, f, Math.PI, s, o);
System.out.printf("Dwa inty: %03d %-5d, float: %+,1.3f %1.20f, stringi: %s %s%n",
x, y, f, Math.PI, s, o);
System.out.printf("%1$f %1$20.10f%n", Math.PI);
}
}
package p36_lokalizacja.formatowanie;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateFormat {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat f = new SimpleDateFormat();
System.out.println(f.format(now));
f.applyPattern("dd.MM.yyyy");
System.out.println(f.format(now));
f.applyPattern("d MMM , H:mm");
System.out.println(f.format(now));
f.applyLocalizedPattern("dd.MM.yyyy");
System.out.println(f.format(now));
SimpleDateFormat f2 = new SimpleDateFormat("dd MMMM");
System.out.println(f2.format(now));
}
}
package p36_lokalizacja.formatowanie;
import java.text.DecimalFormat;
public class TestDecimalFormat {
public static void main(String[] args) {
double number = 123456.45;
DecimalFormat df1 = new DecimalFormat();
//df1.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(new Locale("pl")));
System.out.println(df1.format(number));
df1.applyPattern("00000.000");
System.out.println(df1.format(number));
df1.applyLocalizedPattern("00000,000");
System.out.println(df1.format(number));
df1.applyPattern("#.0#");
System.out.println(df1.format(number));
DecimalFormat df2 = new DecimalFormat("##,##.#");
System.out.println(df2.format(number));
}
}
package p36_lokalizacja.formatowanie;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class TestDecimalFormat2 {
public static void main(String[] args) {
Locale locale = new Locale("de", "DE");
double number = 1246.36;
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(locale);
System.out.println(df.format(number));
df.applyPattern("0.0E00");
System.out.println(df.format(number));
df.applyLocalizedPattern("0,0##E0");
System.out.println(df.format(number));
}
}
package p36_lokalizacja.formatowanie;
import java.util.Currency;
import java.util.Locale;
public class Waluty {
public static void currencyInfo(Locale locale) {
Currency currency = Currency.getInstance(locale);
System.out.println("code: "
+ currency.getCurrencyCode());
System.out.println("symbol: "
+ currency.getSymbol());
System.out.println("displayName: "
+ currency.getDisplayName());
}
public static void main(String[] args) {
Locale[] all = {
new Locale("pl", "PL"),
new Locale("de", "DE"),
new Locale("fr", "FR"),
new Locale("en", "GB"),
new Locale("en", "US"),
//new Locale("en"),
};
for (Locale locale : all) {
System.out.println("Dla locali " + locale.toString());
currencyInfo(locale);
System.out.println();
}
}
}
package p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 p41_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 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 p41_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));
System.out.println(para1);
Number lewy = para1.getLewy();
Integer lewyi = para1.getLewy();
//NK para1.setLewy(new Double(3.14));
para1.setLewy(new Integer(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 p42_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 p42_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 p42_refleksja.klasy;
public class BrakSrodkow extends Exception {
public BrakSrodkow() {
super();
}
public BrakSrodkow(String message) {
super(message);
}
}
package p42_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 p42_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 p42_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 p42_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 p42_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 p42_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 p42_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 p42_refleksja.sklep_model;
import java.lang.reflect.Field;
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();
}
}
......@@ -12,5 +12,4 @@ import java.time.LocalDate;
- toString, equals i hashCode (przypominające standardowe implementacje generowane przez IDE)
*/
public record Rekord(LocalDate data, String miasto, String sklep, String kategoria, String towar, BigDecimal cena, int sztuk) {
}
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