public class AClass Intann vs triedne public int
public class AClass { Inštančné vs. triedne public int instance. Integer = 0; public int instance. Method() { return instance. Integer; } public static int class. Integer = 0; public static int class. Method() { return class. Integer; } public static void main(String[] args) { AClass an. Instance = new AClass(); AClass another. Instance = new AClass(); an. Instance. instance. Integer = 1; another. Instance. instance. Integer = 2; System. out. println( an. Instance. instance. Method()); System. out. println( another. Instance. instance. Method()); //System. out. println(instance. Integer); AClass. class. Integer = 7; System. out. println(class. Method()); System. out. println(an. Instance. class. Method()); an. Instance. class. Integer = 9; System. out. println(an. Instance. class. Method()); System. out. println( another. Instance. class. Method()); } } 1 2 7 7 9 9
Konvencie • • • 80% životného cyklu software spotrebuje jeho údržba, málokedy je software celý cyklus udržiavaný jedným programátorom, autorom. . . konvencie kódovania majú uľahčiť čitateľnosť kódu iným, či aj mne po rokoch preto: http: //java. sun. com/docs/codeconv/html/Code. Conv. TOC. doc. html Triedy, napr. : class Raster; class Image. Sprite; Meno triedy je podstatné meno, každé podslovo začína veľkým písmenkom (mixed case), celé meno začína veľkým písmenom. Meno je jednoduché a dobre popisujúce. Metódy, napr. : run(); run. Fast(); get. Background(); Mená metód sú slovesá, začínajú malým písmenom. Premenné, napr. int i; char c; float my. Width; Začínajú malým písmenom, mixed case, nezačínajú _ resp. $ Jednopísmenkové mená sú na dočasné premenné. Konštanty, napr. static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1; Veľkými, slová oddelené ("_").
• • • Dedičnosť class A extends B. . . pridanie novej funkcionality (premenných a metód) predefinovanie existujúcich funkcií predka (override) vzťah is-a vs. is-like-a dynamic binding = polymofizmus void do. Stuff(Shape s) { s. erase(); //. . . s. draw(); } Circle c = new Circle(); Triangle t = new Triangle(); Line l = new Line(); do. Stuff(c); do. Stuff(t); do. Stuff(l);
this public class Rectangle { public class HSBColor { private int hue, saturation, brightness; public HSBColor ( int hue, int saturation, int brightness) { this. hue = hue; this. saturation = saturation; this. brightness = brightness; } } private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle( int x, int y, int width, int height) { this. x = x; this. y = y; this. width = width; this. height = height; } . . . }
super public class Superclass { public boolean a. Variable; public void a. Method() { a. Variable = true; } } public class Subclass extends Superclass { public boolean a. Variable; //overrides a. Variable in Superclass public void a. Method() { //overrides a. Method in Superclass a. Variable = false; super. a. Method(); System. out. println(a. Variable); System. out. println(super. a. Variable); } } false true
Konštruktor nadtriedy class A { A() { System. out. println("A constructor"); } } class B extends A { B() { System. out. println("B constructor"); } } public class C extends B { C() { System. out. println("C constructor"); } public static void main(String[] args) { C x = new C(); } } A constructor B constructor C constructor
Konštruktor nadtriedy class A { A(int i) { System. out. println("A constructor"); } } class B extends A { B(int i) { super(i); System. out. println("B constructor"); } } public class C extends B { C() { super(11); System. out. println("C constructor"); } public static void main(String[] args) { C x = new C(); } } A constructor B constructor C constructor
Kompozícia class A { A(int i) { System. out. println("A constructor"); } } class B { B(int i) { System. out. println("B constructor"); } } class C extends B { C(int i) { super(i); System. out. println("C constructor"); } } class D extends B { D(int i) { super(i); System. out. println("D constructor"); } } class E { E(int i) { System. out. println("E constructor"); } } public class F extends E { C c; // kompozícia objektov D d; A a; F(int i) { super(i + 1); c = new C(i + 2); d = new D(i + 3); a = new A(i + 5); System. out. println("F constructor"); } public static void main(String[] args) { F f = new F(9); } } E, B, C, B, D, A, F
Metódy abstract class Graphic. Object { int x, y; . . . void move. To(int new. X, int new. Y) { . . . } abstract void draw(); } class Circle extends Graphic. Object { void draw() {. . . } } class Rectangle extends Graphic. Object { void draw() {. . . } }
Triedy a metódy final neexistuje inštancia, resp. nemožno overridovať, dôvody, napr. : • bezpečnosť, . . . • softwarový návrh, . . . final class Chess. Algorithm { . . . } class Chess. Algorithm { . . . final void next. Move (CPiece piece. Moved, Board. Location new. Location) { . . . }
public class Stack { protected int[] S; protected int top = -1; Moj prvy Stack // reprezentácia public Stack(int Size) { S = new int[Size]; } public int size() { return (top + 1); } public boolean is. Empty() { return (top < 0); } public void push(int element) { if (size() == S. length) System. out. println("Stack is full. "); S[++top] = element; } public int pop() { int element; if (is. Empty()) { System. out. println("Stack is empty. "); return -1; } element = S[top--]; return element; } } class Main { public static void main(String[] args) { final int SSIZE = 100; Stack s = new Stack(SSIZE); for(int i=0; i<SSIZE; i++) s. push(i); while (!(s. is. Empty())) { System. out. println(s. pop()); } } }
Stack ++ public class Stack { protected Object[] S; protected int top; public Stack (int Size) { this. S = new Object[Size]; this. top = 0; } public boolean is. Empty () { return top == 0; } public void push (Object item) { S[top] = item; top++; } public Object pop () { top--; return S[top]; } } import java. util. Stack; ……. Stack pd = new Stack(); pd. push(new Integer(123456)); pd. push("ahoj"); String s = (String)pd. pop(); Integer numb = (Integer)pd. pop(); public void push (Object item) { if (top == S. length) { Object[] new. S = new Object[S. length * 2]; for (int i=0; i<S. length; i++) { new. S[i] = S[i]; } S = new. S; }
Stack – templates (v. 5. 0) public class Stack<E> { protected E[] S; protected int top; public Stack (int Size) { S = (E[]) new Object[Size]; top = 0; } public boolean is. Empty () { return top == 0; } public void push (E item) { S[top] = item; top++; } public E pop () { top--; return S[top]; } } Stack<String> st = new Stack<String>(); st. push("caf"); String s = st. pop();
Parent [(()())[()]] public void check. Parent(String input) { int stack. Size = input. length(); Stack the. Stack = new Stack(stack. Size); for (int j = 0; j < input. length(); j++) { char ch = input. char. At(j); switch (ch) { case '[': case '(': the. Stack. push(ch); break; case ']': case ')': if (!the. Stack. is. Empty()) { char chx = the. Stack. pop(); if ((ch == ']' && chx != '[') || (ch == ')' && chx != '(')) return false; } else return false; break; } } return (the. Stack. is. Empty()); }
Stack - interface public class Empty. Stack. Exception extends Runtime. Exception { public Empty. Stack. Exception(String err) { super(err); } } public class Full. Stack. Exception extends Runtime. Exception { public Full. Stack. Exception(String err) { super(err); } } public interface Stack<E> { public int size(); public boolean is. Empty(); public E top() throws Empty. Stack. Exception; public void push (E element) throws Full. Stack. Exception; public E pop() throws Empty. Stack. Exception; }
Stack – implementation public class Array. Stack<E> implements Stack<E> { protected int capacity; protected E S[]; protected int top = -1; public Array. Stack() { this(1000); } public Array. Stack(int cap) { capacity = cap; S = (E[]) new Object[capacity]; } . . public void push(E element) throws Full. Stack. Exception { if (size() == capacity) throw new Full. Stack. Exception("Stack is full. "); S[++top] = element; } public E top() throws Empty. Stack. Exception { if (is. Empty()) throw new Empty. Stack. Exception("Stack is empty. "); return S[top]; }
Stack - main public E pop() throws Empty. Stack. Exception { E element; if (is. Empty()) throw new Empty. Stack. Exception("Stack is empty. "); element = S[top]; S[top--] = null; // dereference S[top] for garbage collection. return element; } public String to. String() { String s; s = "["; if (size() > 0) s+= S[0]; if (size() > 1) for (int i = 1; i <= size()-1; i++) s += ", " + S[i]; return s + "]"; } public static void main(String[] args) { Array. Stack<String> B = new Array. Stack<String>(); B. push("Bob"); B. push("Alice"); Object o = B. pop(); B. push("Eve"); } }
Java Collections • interface • implementation • algorithm
Interface public interface Collection<E> extends Iterable<E> { int size(); boolean is. Empty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); …. Object[] to. Array(); <T> T[] to. Array(T[] a); }
Iterator public interface Iterator<E> { boolean has. Next(); E next(); void remove(); //optional } static void filter(Collection<? > c) { for (Iterator<? > it = c. iterator(); it. has. Next(); ) if (!cond(it. next())) it. remove(); } for (Object o : collection) System. out. println(o);
Implementations Hash Table Collection Set Hash Set Resizable Array Balanced Tree Linked List Array. List Tree. Set Linked. List Tree. Set Sorted. Set Interface Tree. Set List Map Sorted. Map Array. List Hash Map Linked. List Tree. Map
Interface vs. Implementation 1. 2. 3. 4. 5. 6. 7. Array. List nemusí byť prealokovaný pri náraste Linked. List a Array. List možno použiť ako FIFO (list. add() / list. remove(0)) Tree. Map a Tree. Set sú usporiadané, potrebujú porovnanie Set a Map nemôžu obsahovať duplikáty Map obsahuje páry (key; object) prístupné cez kľúč key Prvky môžu byť indexované Prvky možeme prechádzať sekvenčne Najčastejšia implementácia 1. Set interface ako Hash. Set 2. List interface ako Array. List 3. Map interface ako Hash. Map 4. Queue interface ako Linked. List
import java. util. *; Set/Hash. Set public class Find. Duplicates { public static void main(String[] args) { public interface Set<E> extends Collection<E> { int size(); boolean is. Empty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Array Operations Object[] to. Array(); <T> T[] to. Array(T[] a); } Set<String> s = new Hash. Set<String>(); for (String a : args) if (!s. add(a)) System. out. println("Duplicate : " + a); System. out. println(s. size() + " distinct words: " + s); } } java Find. Dups i came i saw i left Duplicate : i 4 distinct words: [i, left, saw, came]
Sorted. Set/Tree. Set import java. util. Arrays; import java. util. Iterator; import java. util. Sorted. Set; import java. util. Tree. Set; public interface Sorted. Set<E> extends Set<E> { Sorted. Set<E> sub. Set(E from. Element, E to. Element); Sorted. Set<E> head. Set(E to. Element); Sorted. Set<E> tail. Set(E from. Element); // Endpoints E first(); E last(); // Comparator access Comparator<? super E> comparator(); } Sorted. Set sorted. Set = new Tree. Set(Arrays. as. List( "one two three four five six seven eight". split(" "))); System. out. println(sorted. Set); // eight, five, four, one, seven, six, three, two Object low = sorted. Set. first(), high = sorted. Set. last(); // eight, two Iterator it = sorted. Set. iterator(); for (int i = 0; i <= 6; i++) { if (i == 3) low = it. next(); // one if (i == 6) high = it. next(); // two else it. next(); } System. out. println(sorted. Set. sub. Set(low, high)); // one, seven, six, three System. out. println(sorted. Set. head. Set(high)); // eight, five, four, one, seven, six, three System. out. println(sorted. Set. tail. Set(low)); // one, seven, six, three, two
import java. util. *; List/Array. List public class List. Demo { public static void main(String[] args) { String[] p = {"a", "b", "c", "d"}; List <String> s = new Array. List<String>(); for (String a : p) s. add(a); for (Iterator it = s. iterator(); it. has. Next(); ) System. out. println(it. next()); a b c d d foo a s. set(1, "foo"); s. remove(2); for (List. Iterator<String> it = s. list. Iterator(s. size()); it. has. Previous(); ) System. out. println(it. previous()); } }
List public interface List<E> extends Collection<E> { // Positional access E get(int index); E set(int index, E element); boolean add(E element); void add(int index, E element); E remove(int index); boolean add. All(int index, Collection<? extends E> c); int index. Of(Object o); int last. Index. Of(Object o); // Search // Iteration List. Iterator<E> list. Iterator(); List. Iterator<E> list. Iterator(int index); List<E> sub. List(int from, int to); } // Range-view
import java. util. *; Map/Hash. Map public class Freq { public static void main(String[] args) { Map<String, Integer> m = new Hash. Map<String, Integer>(); for (String a : args) { Integer freq = m. get(a); m. put(a, (freq == null) ? 1 : freq + 1); } System. out. println(m); } } java Freq if it is to be it is up to me to delegate {to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}
import java. util. *; Ordered public class Name. Sort { public static void main(String[] args) { Name name. Array[] = { new Name("John", "Lennon"), new Name("Karl", "Marx"), new Name("Groucho", "Marx"), new Name("Oscar", "Grouch") }; List<Name> names = Arrays. as. List(name. Array); Collections. sort(names); System. out. println(names); } }
Comparable public class Name implements Comparable<Name> { private final String first. Name, last. Name; public Name(String first. Name, String last. Name) {. . . } public String first. Name() {. . . } public String last. Name() {. . . } public String to. String() {. . . } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n. first. Name. equals(first. Name) && n. last. Name. equals(last. Name); } public int compare. To(Name n) { int last. Cmp = last. Name. compare. To(n. last. Name); return (last. Cmp != 0 ? last. Cmp : first. Name. compare. To(n. first. Name)); } }
Vnorené triedy class Enclosing. Class { . . . class ANested. Class { . . . } } class Enclosing. Class { . . . static class Static. Nested. Class { . . . } class Inner. Class { . . . } }
Vnorené triedy anonymné public class Stack { private Object[] items; public Iterator iterator() { return new Stack. Iterator(); } public Iterator iterator() { return new Iterator() { int current. Item = items. size() - 1; public boolean has. Next() { . . . } public Object next() { . . . } public void remove() { . . . } } } class Stack. Iterator implements Iterator { int current. Item = items. size() - 1; public boolean has. Next() { . . . } public Object next() { . . . } public void remove() { . . . } } }
- Slides: 31