Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor

316 vues

Publié le

Курс "Программирование на Java". Лекция 04 "Обобщения и лямбды".

Массивы. Механизм обобщений (Generics), надтипы и подтипы (supertypes and subtypes). Лямбда-функции, функциональные интерфейсы. Пакет java.util.collections, списки (Lists), множества (Sets), словари (Maps), итераторы (Iterators and Iterables). Иерархия коллекций.

МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич

Publié dans : Logiciels
  • Soyez le premier à commenter

Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor

  1. 1. 4. Обобщения и лямбды Программирование на Java Федор Лаврентьев МФТИ, 2016
  2. 2. Массивы
  3. 3. Массив int[] ints = new int[10]; assert ints.length == 10; for (int i = 0; i < ints.length; ++i) { ints[i] = i * i; } Object arr = ints; // Array is an object final Object[] objects = new Object[1]; objects = new Object[1]; // WRONG objects[0] = arr; // But right o_O
  4. 4. Инициализация массивов double[] coeffs = {3.0, 4.0, 5.0}; int[][] intMatrix = new int[3][4]; // 0 -> [0, 0, 0, 0] // 1 -> [0, 0, 0, 0] // 2 -> [0, 0, 0, 0] char[][] words = {{‘a’, ‘b’, ’c’}, {‘d’, ‘e’}}; // 0 -> [‘a’, ‘b’, ‘c’] // 1 -> [‘d’, ‘e’]
  5. 5. Многомерный массив int[][] intChain = new int[3][]; // 0 -> null // 1 -> null // 2 -> null for (int i = 0; i < intChain.length; ++i) { intChain[i] = new int[i ** i]; } // 0 -> [] // 1 -> [0] // 2 -> [0, 0, 0, 0]
  6. 6. Обобщённые типы Подробнее здесь: https://docs.oracle.com/javase/tutorial/java/generics/index.html
  7. 7. Логика не зависит от типов аргументов public class Pair { final Object left; final Object right; public Pair(Object left, Object right) { this.left = left; this.right = right; } public Object getLeft() { return left; } public Object getRight() { return right; } }
  8. 8. Уточнение типов усложняет код Pair pair = new Pair(42, “Forty two”); Object leftObj = pair.getLeft(); Integer left = (Integer) leftObj; String right = (String) pair.getRight();
  9. 9. Приведение типов потенциально опасно public long extractLongLeft(Pair pair) { Object leftObj = pair.getLeft; if (!(leftObj instanceof Long)) { throw new IllegalArgumentException(); } Long leftLong = (Long) leftObj; return leftLong.longValue(); // Unnecessary }
  10. 10. Generics (обобщения) public class Pair<A, B> { private final A left; private final B right; public Pair(A left, B right) { this.left = left; this.right = right; } public A getLeft() { return left; } public B getRight() { return right; } }
  11. 11. Generics (обобщения) Pair<Integer, String> p1 = new Pair<Integer, String> (42, “Forty two”); String right1 = p1.getRight(); // “Forty two” Pair<Long, String> p2 = new Pair<>(0L, “Null”); Long left1 = p2.getLeft(); // 0L
  12. 12. Generics: Go deeper public static <A, B> Pair<A, B> pair(A a, B b) { return new Pair<>(a, b); } Pair<Pair<String, Double>, Pair<Long, Byte>> p = pair( pair(“Foo”, 3.14), pair(Long.MAX_VALUE, Byte.MAX_VALUE) ); Pair rawPair = p; // Generic types lost
  13. 13. Подтипы public interface Comparable<T> { boolean geq(T other) default { this.hashCode() >= other.hashCode(); } } public class Comparables { public static <T extends Comparable> T min(T a, T b) { if (a.geq(b)) return b else return a; } public static <T extends Comparable> T max(T a, T b) { if (a.geq(b)) return a else return b; } }
  14. 14. Подтипы import static Comparables.*; class SortedPair<T extends Comparable> extends Pair<T, T> { public SortedPair(T a, T b) { super(min(a, b), max(a, b)) } }
  15. 15. Wildcard public class Pairs { public static <T> T toLeft(Pair<T, ?> pair) { return pair.getLeft(); } public static <T> T toRight(Pair<? extends Object, T> pair) { return pair.getRight() } } public class Zoo { void addAnimal(Animal animal) { ... } void addAnimals(List<? extends Animal> animals) { ... } void addAnimals(List<Dog> dogs) { ... } }
  16. 16. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; public static <T> Pair<int, T> empty() { return new Pair<>(0, new T()); } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  17. 17. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { return new Pair<>(0, new T()); } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  18. 18. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  19. 19. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { Pair<A, B>[] pairs = new Pair<>[n]; ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  20. 20. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { // WRONG Pair<A, B>[] pairs = new Pair<>[n]; // WRONG ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  21. 21. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { // WRONG Pair<A, B>[] pairs = new Pair<>[n]; // WRONG ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { // WRONG Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; } } }
  22. 22. Ограничения обобщений public class Pair<A, B> { private static final A DEFAULT_LEFT; // WRONG public static <T> Pair<int, T> empty() { // WRONG return new Pair<>(0, new T()); // WRONG } public Pair<A, B>[] times(int n) { // WRONG Pair<A, B>[] pairs = new Pair<>[n]; // WRONG ... } public static boolean animalsEquals(Pair<Animal, Animal> pair) { if (pair instanceof Pair<Dog, Dog>) { // WRONG Pair<Dog, Dog> dogsPair = (Pair<Dog, Dog>) pair; // WRONG } } }
  23. 23. Лямбды
  24. 24. Функциональный интерфейс public interface Runnable { void run(); } public class HelloRunnable implements Runnable { @Override public void run() { System.out.println(“Hello!”); } } Thread t = new Thread(new HelloRunnable()); t.start();
  25. 25. Функциональный интерфейс public interface Runnable { void run(); } Thread t = new Thread(new Runnable() { @Override public void run() { System.out.println(“Hello!”); } }); t.start();
  26. 26. Функциональный интерфейс public interface Runnable { void run(); } Thread t = new Thread(() -> { System.out.println(“Hello!”); }); t.start();
  27. 27. Функциональный интерфейс @FunctionalInterface public interface Runnable { void run(); } Thread t = new Thread(() -> { System.out.println(“Hello!”); }); t.start();
  28. 28. Лямбда-выражение @FunctionalInterface interface Comparator<T> { int compare (T first, T second); } Comparator<String> с1 = (String a, String b) -> a.length() – b.length(); Comparator<String> c2 = (a, b) -> a.length() – b.length(); Comparator<String> c3 = (a, b) -> { int lengthA = (a == null) ? 0 : a.length(); int lengthB = (b == null) ? 0 : b.length(); return lengthA – lengthB; }
  29. 29. Применение лямбда-функций public class Comparators { public static int firstCharDiff(String a, String b) { return a.charAt(0) - b.charAt(0) } public static Comparator<String> byNthLetter(int n) { return (a, b) -> a.charAt(n-1) – b.charAt(n-1); } public static <T> void sort<T> (T[] array, Comparator<T> comparator) { ... } } String[] strings = {“burr”, “yamm”, “foorr”}; Comparators.sort(Comparators::firstCharDiff); Comparators.sort(Comparators.byNthLetter(2));
  30. 30. Основные структуры данных
  31. 31. Упорядоченный список (List) List<Dog> dogs = Arrays.asList( new Dog(“Billy”, “Bloodhound”), new Dog(“Jackie”, “Bulldog”) ); List<Animal> animals = new ArrayList<>(4); animals.addAll(dogs); animals.add(0, new Dog(“Pooker”, “Mongrel”)); animals.add(new Cat(“Snowee”, “Birman”)); List<Cat> cats = new LinkedList<>(); cats.add(new Cat(“Snowee”, “Birman”)); animals.containsAll(cats); // true animals.get(0); // Pooker
  32. 32. List processing List<Animal> animals = ...; int totalTeeth = 0 for (int i = 0; i <= animals.size(); ++i) { Animal a = animals.get(i); if (!(a instanceof Dog)) { continue; } Dog d = (Dog) a; totalTeeth += d.getTeethCount(); }
  33. 33. Stream List<Animal> animals = ...; Stream<Animal> stream = animals.stream(); int totalTeeth = stream .filter(a -> a instanceof Dog) // Stream<Animal> .map(a -> (Dog) a) // Stream<Dog> .mapToInt(Dog::getTeethCount) // IntStream .sum(); // int
  34. 34. Уникальное множество (Set) Set<Set> unique = new TreeSet(“Billy”, “Annett”, “Jane”, “Мишаня”, “Pooker”, “Billy”); unique.size(); // 5 (не 6!) unique.headSet(“July”).foreach(System.out::println); // Annett, Billy, Jane unique.contains(“Annett”); // true
  35. 35. Отображение Словарь (Map) Map<String, Animal> byName = new HashMap<>(); animals.stream() .foreach(a -> byName.put(a.getName(), a)) byName.contains(“Bloody Joe”); // false Animal pooker = byName.get(“Pooker”); byName.entrySet().foreach(System.out::println); // random order
  36. 36. Iterable interface Iterable<T> { Iterator<T> iterator(); Spliterator<T> spliterator(); void foreach(Consumer<? super T> consumer>); } List<Animal> animals = ...; for (Iterator<Animal> it = animals.iterator();it.hasNext();) { Animal a = it.next(); ... } for (Animal a: animals) { ... } animals.foreach(a -> ...)
  37. 37. Deeper – Lazy Iterator example class DataBaseIterator<T> implements Iterator<T> { private final int maxId; private final Connection conn; private int currentId = 0; private final Mapper<Query, T> mapper; DataBaseIterator(Connection conn, Mapper<Query, T> mapper) { this.conn = conn; this.mapper = mapper; maxId = conn.queryInt(“select max(id) from t”); } public boolean hasNext() { return currentId <= maxId; } public T next() { return conn .query(“select * from t where id = ?”, currentId++) .map(mapper); } }
  38. 38. http://www.falkhausen.de/en/diagram/html/java.util.Collection.html
  39. 39. http://www.karambelkar.info/downloads/java_collections/Java-Collections_Map-API-ImageMap.html
  40. 40. http://www.sergiy.ca/guide-to-selecting-appropriate-map-collection-in-java/

×