java course 5: enums, generics, assertions
DESCRIPTION
Lecture 5 from the IAG0040 Java course in TTÜ. See the accompanying source code written during the lectures: https://github.com/angryziber/java-courseTRANSCRIPT
Enums, GenericsEnums, Generics& Assertions& Assertions
Java course - IAG0040Java course - IAG0040
Anton KeksAnton Keks 20112011
Lecture 5Lecture 5Slide Slide 22
Java course – IAG0040Anton Keks
Arrays helper classArrays helper class
● Arrays class provides operations on arrays
– asList() - provides a view of an array as a List
– binarySearch() - searches for an element from a sorted array
– equals() - checks two arrays for equality
– fill() - fills an array with the specified element
– sort() - sorts an array (using a tuned QuickSort algorithm)
– toString() - can be used for displaying of arrays
– deepToString() - the same for multidimensional arrays
Lecture 5Lecture 5Slide Slide 33
Java course – IAG0040Anton Keks
Collections helper classCollections helper class
● Provides constants and operations on Collections
– EMPTY_XXX or emptyXXX() - immutable empty collection
– sort(), binarySearch(), fill(), copy(), min(), max(), shuffle(), replaceAll(), rotate(), swap()
– singletonXXX() - immutable collection with one element
– enumeration() - for support of legacy classes
● Wrappers
– checkedXXX() - a dynamically typesafe view
– unmodifiableXXX() - an unmodifiable view
– synchronizedXXX() - a synchronized view
Lecture 5Lecture 5Slide Slide 44
Java course – IAG0040Anton Keks
TipsTips
● Program to interfaces
– List list = new ArrayList();
● Copy (or conversion) constructors
– Set set = new TreeSet(map.values());
● Checking if the Collection is empty
– collection.isEmpty()
– collection.size() == 0 may be very expensive
● Remove all nulls (or other elements):
– collection.removeAll(Collections.singleton(null))
● Convert to arrays
– String[] s = c.toArray(new String[c.size()]);
Lecture 5Lecture 5Slide Slide 55
Java course – IAG0040Anton Keks
Tips (cont)Tips (cont)
● Iterate Maps with Map.Entry if you need both keys and values
– for(Map.Entry e : map.entrySet()) {}
● Initial capacity in case of HashSet, HashMap, and ArrayList
– new ArrayList(512)
● Operations on sublists are reflected in the main lists
– list.subList(15, 16).remove(object);
● All collections implement toString()
– useful for displaying the contents quickly
Lecture 5Lecture 5Slide Slide 66
Java course – IAG0040Anton Keks
Inner classesInner classes
● Inner classes can be defined inside of other classes
– class MyClass {class InnerClass { }
}
– non static inner classes can access internals of parent classes
– static inner classes cannot
Lecture 5Lecture 5Slide Slide 77
Java course – IAG0040Anton Keks
Anonymous inner classesAnonymous inner classes
● Classes can be created and instantiated 'inline'
– Runnable runnable = new Runnable() {public void run() {
System.out.println("Running!");}
};runnable.run();
● Analogous to initialization of arrays: new byte[] {1}● Very useful for implementation of short interfaces, where the
code is needed as part of the surrounding code
● Compiled into ParentClass$1.class, where $1 is the index of the anonymous class within the ParentClass
Lecture 5Lecture 5Slide Slide 88
Java course – IAG0040Anton Keks
AnnotationsAnnotations
● Annotations are special type of interfaces
– @interface MyAnnotation { }
– Allow specification of meta data for source code elements● Used before the element in question, just like Javadoc
– In general, don't have effect at runtime
– Built-in: @SupressWarnings, @Deprecated, @Override, @Generated, etc
– Can take parameters: @SupressWarnings(“unused”)or @SupressWarnings(value=“unused”)
● Very useful in various frameworks, e.g. JUnit4, Spring2, Hibernate3, EJB3
Lecture 5Lecture 5Slide Slide 99
Java course – IAG0040Anton Keks
EnumsEnums
● Special type of class (base class is java.lang.Enum)
● enum Season {WINTER, SPRING, SUMMER, AUTUMN}
● Only one instance of each constant is guaranteed; enums cannot be instantiated; they are implicitly final (cannot be extended)
● Constructors can be used: WINTER(1), SPRING(“Hello”)
● Accessed like constants: Season.WINTER
● Every enum has the following methods:
– int ordinal() - returns an ordinal value of the constant
– String name() - returns the name of the constant
– static Enum valueOf(String name) - returns the enum constant
– static Season[] values() - returns an array of all constants
● See Season and Planet in net.azib.java.lessons.enums
Lecture 5Lecture 5Slide Slide 1010
Java course – IAG0040Anton Keks
Introduction to GenericsIntroduction to Generics
● Are there any problems with collections?
– String s = (String) list.get(3);
● Java 1.5 introduced generics for type safety checks
– List<String> list;String s = list.get(3);
● Additionally, generics allow to abstract over types
– List<Integer> list = Arrays.asList( new Integer[]{1,2});
– List<String> list = Arrays.asList( “a”, “b”, “c”);
● Provide more compile time information for error checking
Lecture 5Lecture 5Slide Slide 1111
Java course – IAG0040Anton Keks
Defining generic classesDefining generic classes
● public interface List<E> {void add(E x);Iterator<E> iterator();
}
● public interface Iterator<E>{E next();boolean hasNext();
}
● Formal type parameters are in the angle brackets <>
● In invocations of generic types (parametrized types), all occurrences of formal types are replaced by the actual argument
● Primitives cannot be used as arguments, but arrays and wrappers can
– Iterator<int[]> i; List<Integer> intList;
Lecture 5Lecture 5Slide Slide 1212
Java course – IAG0040Anton Keks
Defining genericsDefining generics
● Generics can be thought of as if they were expanded
– public interface ListOfIntegers {void add(Integer x);Iterator<Integer> iterator();
}● Actually they are not: generics introduce no memory or
performance overhead
● Information about type parameters is stored in class files and used during compilation
● Use possibly meaningful single character names
– E = Element, T = Type, K = Key, V = Value, etc
Lecture 5Lecture 5Slide Slide 1313
Java course – IAG0040Anton Keks
Generics usage in Java APIGenerics usage in Java API
● Collection<E>, Iterable<E>, Iterator<E>
● Set<E>, List<E>, Queue<E>
– Set<String> set = new HashSet<String>();
– Queue<Dog> q = new LinkedList<Dog>();
● Map<K, V>
– Map<String, Thread> map = new HashMap<String, Thread>();
● Comparator<T>, Comparable<T>
● Class<T>
– Date d = Date.class.newInstance();
Lecture 5Lecture 5Slide Slide 1414
Java course – IAG0040Anton Keks
SubtypingSubtyping
● If A extends B, does List<A> extend List<B>?
● List<String> ls = new ArrayList<String>();List<Object> lo = ls;
– this is illegal – List of Strings is not a List of Objects● lo.add(new Integer(42)); // adds an illegal objectString s = ls.get(0); // this is not a String!
– this code would break type safety at runtime!
● However
– ls instanceof List & lo instanceof List
– Collection<String> cs = ls; // legal
Lecture 5Lecture 5Slide Slide 1515
Java course – IAG0040Anton Keks
Backward compatibilityBackward compatibility
● Generics are backward compatible
– Java 1.5 still had to be able to run old (unparameterized) code
– Backward compatibility has influenced the implementation
● Old-style (unparameterized or raw-type) code can still be written
– ArrayList al = new ArrayList<String>();ArrayList<String> al = new ArrayList();
● For now, checks are only done at compile time
– At runtime, generic collections hold Objects ('type erasure')
– Collections.checkedXXX() methods may be used for runtime type checking
– Implementation may change in future
Lecture 5Lecture 5Slide Slide 1616
Java course – IAG0040Anton Keks
WildcardsWildcards
● void printCollection(Collection<Object> c) {for (Object e : c)
System.out.println(e);}
● printCollection(new ArrayList<String>()) // doesn't compile
● void printCollection(Collection<?> c) { // ? is a wildcardfor (Object e : c)
System.out.println(e);}
● However the following fails (at compile time!)
– c.add(new Object());
– Collection<?> means “collection of unknown”, it is read-only
– Unknown <?> can always be assigned to Object (when reading)
Lecture 5Lecture 5Slide Slide 1717
Java course – IAG0040Anton Keks
Bounded wildcardsBounded wildcards
● <? extends T> means “anything that extends T”– upper bounded wildcard, “read-only”
– List<? extends Number> vs List<Number>
– List<Integer> can be assigned to the first one, but not to the second one
– add() still doesn't work, because actual type is not known
● <? super T> means “anything that is a supertype of T”– lower bounded wildcard, “write-only”
– List<? super Number> vs List<Number>
– add(new Integer(5)) works, because Integer can be assigned to any supertype of Number or Number itself
Lecture 5Lecture 5Slide Slide 1818
Java course – IAG0040Anton Keks
Generic methodsGeneric methods
● Methods can also be generic, independently from their classes
● Generic methods can substitute wildcard types
– boolean containsAll(Collection<?> c);<T> boolean containsAll(Collection<T> c);
● But it is more reasonable to use in case a type is used many times
– <T> void copy(List<T> dest, List<? extends T> src);<T, S extends T> void copy(
List<T> dest, List<S> src);
● T is selected automatically based on the passed types (it is always the most specific type possible), its usage is implicit
● Relative type dependencies are important (extends / super)
Lecture 5Lecture 5Slide Slide 1919
Java course – IAG0040Anton Keks
Generics tasksGenerics tasks
● Use generics in WordFrequencyCalculatorImpl and DuplicateRemoverImpl
● Write some new classes– Circle and Square
● both should extend the provided net.azib.java.lessons.collections.Shape
– ShapeAggregatorImpl (which should implement the ShapeAggregator)
Lecture 5Lecture 5Slide Slide 2020
Java course – IAG0040Anton Keks
AssertionsAssertions
● assert keyword can be used for assertion of validity of boolean expressions (a debugging feature)– assert boolean-expression : value-expression;
– assert A == 5 : “A is not 5!!!”;
● If boolean-expression evaluates to false, an AssertionError is thrown with the value-expression as detailed message (optional)
● Assertions are disabled by default, therefore have no runtime overhead
● When enabled, help to write self-documented code and trace bugs at runtime
● java -ea switch enables assertions (specific packages and classes may be specified if global activation is not desired)