Generics are facilities of generic programming that was added to the Java programming language in 2004 as part of J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety." This report presents an overview on how Generics are implemented in Java.
Презентация для JuJa вебинара о том, как писать рекурсивные программы с примером о вычислении факториала и чисел Фибоначчи. Также рассказывается о поиске линейном, бинарном, в глубину и в ширину, как работает поисковая система.
Презентация сделана для новичков в деле программистов.
Презентация для JuJa вебинара о том, как писать рекурсивные программы с примером о вычислении факториала и чисел Фибоначчи. Также рассказывается о поиске линейном, бинарном, в глубину и в ширину, как работает поисковая система.
Презентация сделана для новичков в деле программистов.
Olexandra Dmytrenko
QA Automating at EPAM Systems
I'll show you how to switch from writing standard code using good old Java7 into writing it using functional way presented in Java8. The training is counted on beginners in the subject who like discovering the new horizons or for those who want to become more firm in using the new lambda features.
Лекция 8. Итераторы, генераторы и модуль itertools.Roman Brovko
Два протокола итераторов: __next__ + __iter__ и __getitem__. Итераторы и цикл for, а также операторы in и not in. Генераторы, оператор-выражение yield. Генераторы как: итераторы, сопрограммы, менеджеры контекста. Модуль itertools.
If you've programmed in Java in the past decade then you know what generic types are. Generics are used everywhere but rarely understood on a deep level. In this talk, Bryan will show not only classic "container" generic classes but also how to build simple, but highly flexible frameworks in all tiers (GUI, Service and DAO tiers).
Olexandra Dmytrenko
QA Automating at EPAM Systems
I'll show you how to switch from writing standard code using good old Java7 into writing it using functional way presented in Java8. The training is counted on beginners in the subject who like discovering the new horizons or for those who want to become more firm in using the new lambda features.
Лекция 8. Итераторы, генераторы и модуль itertools.Roman Brovko
Два протокола итераторов: __next__ + __iter__ и __getitem__. Итераторы и цикл for, а также операторы in и not in. Генераторы, оператор-выражение yield. Генераторы как: итераторы, сопрограммы, менеджеры контекста. Модуль itertools.
If you've programmed in Java in the past decade then you know what generic types are. Generics are used everywhere but rarely understood on a deep level. In this talk, Bryan will show not only classic "container" generic classes but also how to build simple, but highly flexible frameworks in all tiers (GUI, Service and DAO tiers).
Understanding bytecode and what bytecode is likely to be generated by a Java compiler helps the Java programmer in the same way that knowledge of assembler helps the C or C++ programmer. Java bytecode is the form of instructions that Java virtual machine executes. This knowledge is crucial when debugging and doing performance and memory usage tuning. The presenter will share his knowledge on what bytecode means for your platform and how to create compiler while using some awesome tools.
Generics were added to the Java language more than 10 year ago. But do you really understand them?
We’ll discuss:
What is heap pollution?
How does the compiler translate generics?
Why it’s not allowed to create parametrized array (List<string>[])
What are bridge methods, can we reach them?
Type erasure rules
Difference between List, List<object>, List<?>
Why it’s not allowed to add Integer to List<?>
Why it’s not allowed to parameterize exception classes?
What’s wrong with Collections.max signature: <t><?>> T max(Collection<?> coll);
Code that should be compiled, but can’t be compiled and vice versa
How to write good API using generics and wildcards
And other generic puzzlers
Java 8, самой заметной фичей которой стало появление лямбд, вышла два года назад, а в этом году мы даже начали её использовать в продакшен коде Идеи. Такое заметное нововведение в языке вызывает множество вопросов. Какие возможности перед нами открываются и какие проблемы при неаккуратном использовании лямбд могут возникнуть, как лямбды устроены внутри, во что они компилируются и как исполняются — вот темы, которые мы обсудим на докладе.
2. Generics в Java
1. Простые generic-и
1.List strList = new ArrayList();
2.strList.add("some text");
3.// ??!! O_o
4.strList.add(new Integer(0));
5.String str = (String)strList.get(0);
6.// ClassCastException
7.Integer i = (Integer)strList.get(0);
3. Generics в Java
1. Простые generic-и
1.List<String> strList = new ArrayList<String>();
2.strList.add("some text");
3.strList.add(new Integer()); // сообщение об ошибке компилятора
4.String str = strList.get(0);
5.Integer i = strList.get(0); //сообщение об ошибке компилятора
4. Generics в Java
1. Простые generic-и
1.class GenericList<E>{
2. E getFirst() { ... }
3. void add(E obj) { ... }
4.}
1.GenericList<String> genericList = new GenericList<String>();
5. Generics в Java
2. Generic-методы
1.public class CreateAnArrayList {
2. public <T> void makeArrayList(T t) { // take an object of an
3. // unknown type and use a
4. // "T" to represent the type
5. List<T> list = new ArrayList<T>(); // now we can create the
llist using "T"
6. list.add(t);
7. }
8.}
1.public void makeArrayList(Integer t) {
2. List<Integer> list = new ArrayList<Integer>();
3. list.add(t);
4.}
6. Generics в Java
2. Generic-методы
1.public class GenMethDemo {
2.// Determine if an object is in an array.
3.static <T> boolean isIn(T x, T[] y) {
4. for(int i=0; i < y.length; i++)
5. if(x.equals(y[i])) return true;
6. return false;
7.}
8.public static void main(String args[]) {
9. // Use isIn() on Integers.
10. Integer nums[] = { 1, 2, 3, 4, 5 };
11. if(isIn(2, nums))
12. System.out.println("2 is in nums");
13. // Use isIn() on Strings.
14. String strs[] = { "one", "two", "three", "four", "five" };
15. if(isIn("two", strs))
16. System.out.println("two is in strs");
17. // Opps! Won"t compile! Types must be compatible.
18. if(isIn("two", nums))
19. System.out.println("two is in strs");
20. }
21.}
7. Generics в Java
3. Маски (wildcards)
•Предположим, у нас есть функция, которая находит ближайший к
точке Glyph из заданной коллекции. Glyph – это базовый тип, и может
иметься неограниченное количество потомков этого типа. Также
может иметься неограниченное количество коллекций, хранящих
элементы, тип которых соответствует одному из этих потомков.
Хотелось бы, чтобы функция могла работать со всеми подобными
коллекциями, и возвращала элемент, тип которого совпадал бы с
типом элемента коллекции, а не приводился к Glyph.
8. Generics в Java
3. Маски (wildcards)
1.<T> T findNearest(Collection<T> glyphs, int x, int y) { ... }
1.<T extends Glyph> T findNearest(Collection<T> glyphs, int x, int y) {...}
9. Generics в Java
3. Маски (wildcards)
class <T extends Glyph & MoveableGlyph> MoveableGlyphsContainter
static <T, V extends T> boolean isIn(T x, V[] y) {...}
10. Generics в Java
3. Маски (wildcards)
1.public interface Box<T> {
2. public T get();
3. public void put(T element);
4.}
1.public void unbox(Box<?> box) {
2. System.out.println(box.get());//Так можно
3. box.put(new Object());//Так нельзя
4. box.put(box.get());//Так тоже нельзя
5. System.out.println(box.toString());//Так можно
6.}