2. Arrays 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 2
3. Collections 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 3
4. Tips
● 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()]);
Java course – IAG0040 Lecture 5
Anton Keks Slide 4
5. 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 5
6. Inner 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 6
7. Anonymous 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 7
8. Annotations
●
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
Java course – IAG0040 Lecture 5
Anton Keks Slide 8
9. Enums
● 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 9
10. Introduction 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 10
11. Defining 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;
Java course – IAG0040 Lecture 5
Anton Keks Slide 11
12. Defining 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 12
13. Generics 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();
Java course – IAG0040 Lecture 5
Anton Keks Slide 13
14. Subtyping
● 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 object
String 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 14
15. Backward 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 15
16. Wildcards
● 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 wildcard
for (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)
Java course – IAG0040 Lecture 5
Anton Keks Slide 16
17. Bounded 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
Java course – IAG0040 Lecture 5
Anton Keks Slide 17
18. Generic 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)
Java course – IAG0040 Lecture 5
Anton Keks Slide 18
19. Generics 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)
Java course – IAG0040 Lecture 5
Anton Keks Slide 19
20. Assertions
●
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)
Java course – IAG0040 Lecture 5
Anton Keks Slide 20