Android 100%
Android 100%
Overview
Advanced
Generics
programming in Java
Java Collections Framework
Reflection
Ing. Marek Běhálek
katedra informatiky FEI VŠB-TUO
Annotations
A-1018 / 597 324 251 Serializations
http://www.cs.vsb.cz/behalek Streams in Java
[email protected] Thread and Synchronization
all types that are subtypes of Supertype public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
upper-bound wildcard - ? super Subtype //List<Number> li1 = Arrays.asList(inums); //compilation error
//List<? extends Number> li2 = Arrays.asList(inums); //ok
all types that are supertypes of Subtype List<Integer> li = Arrays.asList(inums);
System.out.println(average(li)); //prints 3.0 }
}
static double average(List<? extends Number> nums) static <T extends Number> T median(List<T> nums) {
int pos = nums.size()/2;
return nums.get(pos);
}
An alternative (equivalent) signature: public static void main(String args[]) {
Integer inums[] = { 0, 0, 0, 0, 100};
List<Integer> li = Arrays.asList(inums);
static <T extends Number> double average(List<T> nums) System.out.println(average(li));
System.out.println(median(li));
}
}
The later is called a generic method.
Which is better?
When there are no dependencies between the method
parameters - use wildcards. This way the compiler knows about the dependency
between the input and output arguments.
Advanced programming in Java Advanced programming in Java
WeakHashMap<K,V>
No more need for casting. SortedMap<K,V>
Can only add Point objects to points too. HashMap<E>
Type checking at a compile time.
TreeMap<K,V>
LinkedHashMap<K,V>
Advanced programming in Java Advanced programming in Java
TreeSet, TreeMap require sorting capability It satisfies the rules, so technically yes…
Element or key class must implement java.lang.Comparable interface In practice, will cause programs to be very inefficient.
Or, an appropriate implementation of java.util.Comparator must be
provided
Hash function should generate a wide range of values.
Specifically, should produce a uniform distribution of values.
HashSet, HashMap require hashing capability Facilitates most efficient operation of hash tables.
Element or key class must provide a good implementation of Requirement is that equal objects must produce identical hash values…
Object.hashCode()
Also good if unequal objects produce different hash values.
Reflection – Getting
Reflection – Using Fields Constructors of a class
If f is a Field object, then if c is a Class, then
c.getConstructors() : Constructor[] return an array of all
f.getName() returns the simple name of the field public constructors of class c.
f.getType() returns the type (Class) of the field c.getConstructor( Class … paramTypes ) returns a
f.getModifiers() returns the Modifiers of the field constructor whose parameter types match those given
paramTypes.
f.toString() returns a String containing access
Ex:
modifiers, the type, and the fully qualified field
String.class.getConstructors().length
name
> 15;
Example: public java.lang.String Person.name
String.class.getConstrucor( char[].class, int.class,
f.getDeclaringClass() returns the Class in which int.class).toString()
this field is declared > String(char[], int,int).
note: getFields() may return superclass fields.
Advanced programming in Java Advanced programming in Java
a = new int[] {1,2,3,4}; All getXXX() methods of Class mentioned above return only
public members of the target (as well as ancestor ) classes,
Array.getInt(a, 2) // 3 but they cannot return non-public members.
Array.setInt(a, 3, 5 ) // a = {1,2,3, 5 }. There are another set of getDeclaredXXX() methods in Class
that will return all (even private or static ) members of
target class but no inherited members are included.
getDeclaredConstructors(), defDeclaredConstrucor(Class…)
s = new String[] { “ab”, “bc”, “cd” };
getDeclaredFields(),
Array.get(s, 1 ) // “bc” getDeclaredField(String)
Array.set(s, 1, “xxx”) // s[1] = “xxx” getDeclaredmethods(),
getDeclaredMethod(String, Class…)
for(Constructor c : cs) */
int search( Object value ) { …
Annotations – Annotation
Annotations – Meta-Annotations Processing
Meta-annotations - types designed for annotating It's possible to read a Java program and take actions based
annotation-type declarations (annotations-of-annotations) on its annotations
To make annotation information available at runtime, the
Meta-annotations: annotation type itself must be annotated with
@Target - indicates the targeted elements of a class in which the @Retention(RetentionPolicy.RUNTIME):
annotation type will be applicable
@Retention(RetentionPolicy.RUNTIME)
TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, etc @interface AnnotationForRuntime
{
@Retention - how long the element holds onto its annotation // Elements that give information for runtime processing
SOURCE, CLASS, RUNTIME }
@Documented - indicates that an annotation with this type should Annotation data can be examined using reflection
be documented by the javadoc tool mechanism, see e.g. java.lang.reflect.AccessibleObject:
<T extends Annotation> T getAnnotation(Class<T>)
@Inherited - indicates that the annotated class with this type is Annotation[] getAnnotations()
automatically inherited boolean isAnnotationsPresent(<Class<? extends Annotation>)
Java I/O – Reading & Writing Java I/O – Reading & Writing
Data Data
Data can come from many Sources & go to Reading
Java I/O – Byte Streams Java I/O – I/O Super Classes (1)
Reader and InputStream define similar APIs but
InputStream
and for different data types
OutoutStream
are abstract int read()
super classes int read(char cbuf[]) Reader
for byte int read(char cbuf[], int offset, int length)
streams (8-bit
data)
int read()
Sub classes
provide int read(byte cbuf[]) InputStream
specialized int read(byte cbuf[], int offset, int length)
behavior
Java I/O – I/O Super Classes (2) Type of I/O Streams Description
CharArrayReader
Use these streams to read from and write to memory.
FileReader Collectively called file streams, these streams are used to read from or write
int write() FileWriter to a file on the native file system.
File
FileInputStream
int write(byte cbuf[]) OutputStream FileOutputStream
int write(byte cbuf[], int offset, int length)
Object N/A
Serializati- ObjectInputStream Used to serialize objects.
on ObjectOutputStream
BufferedReader class can be used for efficient reading Capabilities are added using a design called
of characters, arrays and lines the Decorator Pattern.
BufferedReader in = new BufferedReader(new FileReader("foo.in")); Component 1
+operation() +operation() 1
+operation() +operation()
+addedOperation1() +addedOperation2()
super.operation()
addedOperation2()
}}
in.close();
}
out.close();
} catch (IOException e) {}
P2 CPU
func1 ( ) func2 ( ) func3 ( )
{ { { Medium grain
Threads .... .... .... (control level) P3 CPU
.... .... ....
} } } Function (thread)
time
Threads – Thread/process
states Threads – Thread states (1)
start yield
New state – a Thread newly created.
Runnable – after being started, the Thread can
stop sleep/suspend resume be run. It is put into the “run queue” of
0 1 2 3 4 Threads and waits its turn to run. “Runnable”
run
stop/end suspend does not mean “running”.
dispatch
stop Running – the thread is executing its code. On
stop a uniprocessor machine, at most one thread can
run at a time.
1 – terminated 3 – suspended
2 – running 4 - runnable
Advanced programming in Java Advanced programming in Java
Threads – The wait() Method (2) Threads – The wait() Method (3)
wait() causes the current thread to wait wait() is also similar to yield()
until another thread invokes the notify() Both take the current thread off the execution
method or the notifyAll() method for this stack and force it to be rescheduled
object However, wait() is not automatically put
Upon call for wait(), the thread releases back into the scheduler queue
ownership of this monitor and waits until notify() must be called in order to get a thread
another thread notifies the waiting threads back into the scheduler‟s queue
of the object
Advanced programming in Java Advanced programming in Java
A: Consumed item: 2
Producer producer=new Producer(pool); Produced item: 3
B: Consumed item: 3
Customer consumer1=new Customer(pool,"A"); Produced item: 4
A: Consumed item: 4
Customer consumer2=new Customer(pool,"B"); Produced item: 5
A: Consumed item: 5
Produced item: 6
consumer1.start(); B: Consumed item: 6
Produced item: 7
consumer2.start(); A: Consumed item:
Produced item: 8
7
B: Consumed item: 8
producer.start(); Produced item: 9
B: Consumed item: 9
}
Advanced programming in Java Advanced programming in Java