Advertisement
layr

java_konsp

May 6th, 2014
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 64.77 KB | None | 0 0
  1. Java 7 Beginner's Tutorial (Third Edition) - Budi Kurniawan põhinev konspekt:
  2. ##################################################################################
  3.  
  4.  
  5. - constants have keyword of final, e.g. 'final int minuInt = 50;'
  6. - The result of a division using the / operator is always an
  7. integer. If the divisor does not divide the dividends equally,
  8. the remainder will be ignored. (java.lang.Math sisaldab mõistlikkemaid jagamisi)
  9. - some unary operators (+,-,tilde) and binary ops (+,-,*,/) cause automatic promotion,
  10. i.e. elevation to a wider type such as from byte to int;
  11. - empty statement (i.e lihtsalt ;) is legal;
  12. - statements can be grouped in a block; by definition, block is a sequence of the following
  13. programming elements:
  14. statements
  15. local class declarations
  16. local variable declaration statements
  17. - statement and a statement block can be labeled, e.g. sectionA: x = y + 1;
  18. või lable'dame blocki: start: { //statements }
  19. - The purpose of labeling a statement or a block is so that it
  20. can be referenced by the break and continue statements.
  21. - The break statement can be followed by a label. The
  22. presence of a label will transfer control to the start of the
  23. code identified by the label.(tähendab see ikka seda? imho näitab see millisest
  24. loopist breakida; revision: miks ma seda küll arvasin lol?
  25. - Java does not have a goto statement like in C or C++, and
  26. labels are meant as a form of goto.
  27. - As with break, continue may be followed by a label to
  28. identify which enclosing loop to continue to.
  29. - nagu C#-ski, peavad kõik elemendid klassides resideeruma;
  30. - if you declare a local reference variable within a method but
  31. do not assign an object to it, you will need to assign null to it
  32. to satisfy the compiler, e.g. Book minuBook = null; meetodiväliselt
  33. võib ka vist lihtsalt Book minuBook; deklareerida;
  34. - Class-level reference variables will be initialized when an
  35. instance is created, therefore you do not need to assign
  36. null to them.
  37. - When a program runs, some memory space is
  38. allocated for data. This data space is logically divided into
  39. two, the stack and the heap. Primitives are allocated in the
  40. stack and Java objects reside in the heap.
  41. - When you declare a reference variable, some
  42. bytes are also set aside in the stack, but the memory does
  43. not contain an object's data, it contains the address of the
  44. object in the heap.
  45. - javas jagatakse eri osad 'package'-itesse (i.e. java.lang.reflect etc); kui õigesti mõistan,
  46. siis on see pisut sarnane C# namespace'i kontseptsioonile;
  47. - by convention your package names should be based on your domain name in reverse, i.e. com.playtech
  48. - To group a class in a package use the keyword package followed by the package name.
  49. - A class that has no package declaration is said to
  50. belong to the default package.
  51. - It is a bad idea for a class to not have a package.
  52. - There are four access control modifiers in Java: public,
  53. protected, private, and the default access level.
  54. - class memberite puhul on protected ja defaulti vahe on see, et protected
  55. puhul saavad membereid accessida ka child klasside objektid, kuid default
  56. puhul mitte;
  57. - afaik siis saab child ka parenti defaultile ligi pääseda, kui nad asuvad
  58. samas package'is;
  59. - A Java source file can only contain one public class.
  60. However, it can contain multiple classes that are not
  61. public. (ehk vaid 1 public class per .java fail)
  62. - A public class must be saved in a file that has the same
  63. name as the class, and the extension must be java.
  64. - Classes with the default access level can only be used by
  65. other classes that belong to the same package.
  66. - Access levels to constructors
  67. are the same as those for fields and methods. Therefore,
  68. constructors can have public, protected, default, and private
  69. access levels.
  70. - import käib package'ite kohta, e.g. import java.io.File;
  71. - kui tahad kõiki package'i klasse, siis import java.io.*;
  72. - static keyword may come before or after the access modifier,
  73. kuigi üldiselt pannakse access mod ette;
  74. - static meetodist ei saa kutsuda non-static fielde ega meetodeid;
  75. - You can only declare a static variable in a class level.
  76. You cannot declare local static variables even if the
  77. method is static.
  78. - refrence vars võivad ka olla static; Static reference variables provide a good way of exposing
  79. the same object that needs to be shared among other
  80. different objects.
  81. - tihti on mõistlik final fieldid ka staticuna deklareerida;
  82. - nende naming convention näeb ette all caps ja sõnad underscore'iga eraldatud;
  83. - Static final reference variables are also possible.
  84. However, note that only the variable is final, which means
  85. once it is assigned an address to an instance, it cannot be
  86. assigned another object of the same type.
  87. - If a method declares a local variable that has the same
  88. name as a class-level variable, the former will ‘shadow’ the
  89. latter. To access the class-level variable from inside the
  90. method body, use the this keyword.
  91. - klassis olevate { } vahele lähevad ininialization koodid; staatilise initializationi
  92. jaoks (mida jooksutatakse vaid kord, i.e. java init ajal) kasut. static { //statements; }
  93. - another way to write initialization code is in the
  94. constructor. In fact, initialization code in a constructor is
  95. more noticeable and hence preferable.
  96. - kui on aga mitu konstruktorit, siis on mõistlikum init osa meetodisse wrappida
  97. ning igal konstruktoril seda kutsuda;
  98. - Unused objects are defined as objects that are no
  99. longer referenced or objects whose references are already
  100. out of scope.
  101. - kui õigesti mõistan, siis 'out of scope' tähendab seda, kui objekti enam
  102. mingil põhjusel ei kasutata, nt kui kasutati vaid for loopis, millest on väljutud;
  103. - nagu c#-s, on ka javas stringid reference type'i;
  104. - If you use the
  105. new keyword, the JVM will always create a new instance of
  106. String. With a string literal, you get an identical String
  107. object, but the object is not always new. It may come from a
  108. pool if the string “Java is cool” has been created before.
  109. - string literals on double quote'ide vahel olevad; neid deklareerides ei tohi rida vahetada,
  110. küll aga tohib concateante'ida + märgiga;
  111. - you can concatenate a string w/ a primitive or another object, nt stringi ja int-i võib liita;
  112. - If an object is concatenated with a String, the toString
  113. method of the former will be called and the result used in
  114. the concatenation.
  115. - calling method on String class returns always a new object !!!!!!;
  116. - StringBuffer on sama mis StringBuilder, kuid esimene on multithreaded envide jaoks;
  117. - StingBuilder:
  118. - You can pass a java.lang.CharSequence, a String, or an int.
  119. - default SB objekti capacity on 16chari, kuid võimalusel võiks instatnsieerimisel
  120. juba ära defineerida (nt new StringBuilder(100);)
  121. - meetodid returnivad sama objekti, millele sai meetod kutsutud, seega saab
  122. meetodeid chainida: sb.append("2 ").append("lol");
  123. - arrays are also objects
  124. - fun fact - java.lang.Array klassi pole olemas; arrayd on special Java objektid;
  125. - An array can also contain other arrays, creating an
  126. array of arrays.
  127. - deklareerimine: a) type[] arrayName; b) type arrayName[];
  128. - deklareerimisel veel array objekti ei luua, ega ruumi ei anta; compiler lihtsalt
  129. loob object reference'i;
  130. - üheks arr loomiseks on kasutada new keywordi, nt new int[4], int[] ints = new int[4];
  131. - teiseks võimaluseks on ilma new keywordi kasutamata, nt
  132. String[] names = { "mari", "jüri" };
  133. loob names[] array suurusega 2;
  134. - When an array is created, its components are either
  135. null (if the component type is an object type) or the
  136. default value of the component type (if the array
  137. contains primitives); nt int[] puhul oleks defaultis arr täis nulle (0);
  138. - arrayd laiendada ei saa; kui tahad, siis pead uue array looma:
  139. int[] newArr = Arrays.copyOf(vanaArr, 4); (kus 4 on uue array suurus)
  140. - sh. võib uue array pikkus olla ka väiksem kui original; sel juhul lihtsalt
  141. kopeeritakse uude esimesed original array elemendid;
  142. - igale objektitüübile vastab konkreetne Class objekt (inheritud), mis seda tüüpi kirjeldab.
  143. läbi selle on võimalik ka new keywordi kasutamata uusi instantse luua (miks? sest võib
  144. juhtuda, et sa ei tea loodava tüübi nime. seda tehakse Class klassi forName ning newInstance
  145. meetodite läbi);
  146. - inputi saab kas läbi System.in.read() või läbi Scanner klassi; (viimane eelistatum);
  147. - Conversion from primitive types to corresponding wrapper
  148. objects and vice versa can happen automatically. Boxing
  149. refers to the conversion of a primitive to a corresponding
  150. wrapper instance, such as an int to a java.lang.Integer.
  151. Unboxing is the conversion of a wrapper instance to a
  152. primitive type, such as Byte to byte.
  153. - et meetodile sööta muutuva nr-ga argse, võid kas signatuuris märkida parameetriks listi, või
  154. kasutada varargs-e, nt public void main(String... args); varargs on mosdef parem!
  155. - teksti format käib läbi %s tagide, mitte {0}, {1}... jne;
  156. - kas javas on sama nagu C-s, et %s käib Stringi kohta, %d int-ile jne????
  157. - In Java, by default all classes are
  158. extendible, but you can use the final keyword to prevent
  159. classes from being subclassed (inherited);
  160. - A consequence of the is-a relationship is that it is legal
  161. to assign an instance of a subclass to a reference variable
  162. of the parent type, e.g. Animal animal = new Bird(); (sest bird on alati animal, küll
  163. aga ei kehti vastupidine seaduspära);
  164. - Increasing
  165. the visibility of a method defined in a superclass from
  166. protected to public is allowed. However, reducing visibility
  167. is illegal.
  168. - What if you create a method that has the same
  169. signature as a private method in the superclass? It is not
  170. method overriding, since private methods are not visible
  171. from outside the class.
  172. - You cannot override a final method.
  173. - when you create a child object, all its parent
  174. classes are also instantiated. (hakataksegi kõige tipust instantsieerima);
  175. - You can explicitly call the parent's constructor from a
  176. subclass's constructor by using the super keyword, but
  177. super must be the first statement in the constructor. Using
  178. the super keyword is handy if you want another constructor
  179. in the superclass to be invoked, e.g. super(s);
  180. - super kerywordi kaudu saab ka pääseda ligi parenti overridden field'idele ja
  181. meetoditele
  182. - you can cast a child to parent class - that's called upcasting;
  183. - To upcast a Child object, all you need to do is assign the
  184. object to a reference variable of type Parent.
  185. - in that case you could also cast it back to child (downcasting); this requires
  186. child type in brackets, i.e. Child child2 = (Chiled) parentMisSaiCastitudChildist; //downcasting;
  187. - note: sulge ongi vaid downcastimisel tarvis;
  188. - instanceof keyword: nt if (s instanceof java.lang.Strint)
  189. - kui objekt on null, siis evalueerib false
  190. - if (child instanceof Parent) // evaluates to true, sest subclass is a type of its superclass;
  191. - final keyword klassi puhul preventib seda klassi extendimast, st seda klassi ei saa pärida;
  192. -
  193. + Err handling
  194.  
  195. - ühes catch blockis võib olla mitu exceptionit; need tuleb eraldada pipe'iga,
  196. e.g. catch (ÜksExeption | TeineException e) { }
  197. - ressursside sulgemiseks etc on olemas try-with-resources statement;
  198. - ! not all resources can be automatically closed; only resource classes that implement
  199. java.lang.AutoCloseable can be closed that way;
  200. - All Java exception
  201. classes derive from the java.lang.Exception class.
  202. - If you have several catch blocks and the exception type
  203. of one of the catch blocks is derived from the type of
  204. another catch block, make sure the more specific
  205. exception type appears first. (vastasel juhul püütakse vale catchi poolt kinni; ps!
  206. siia alla kuuluvad ka child klassid)
  207. - meetodi signatuuris võid nii kirja panna: public String minuMeetod(String s) throws NullPointerException {....
  208. - kui mitu errorit, siis eralda signatuuris lihtsalt komadega;
  209. - kui nüüd meetodi sees on vaja throwida, siis: throw new NullPointerException("lel, err");
  210. - method caller selle kinni püüab, siis e.toString() väljastabki 'lel, err';
  211. - constructor can also throw an exception;
  212. - saad ka enda exceptioneid teha, kui extendid java.lang.Exception klassi;
  213. - PS! kui võimalik, siis testi konditsiooni; try blokk on ressursinõudlik.
  214. -
  215.  
  216. + Number/date formatting, parsing and manipulation
  217.  
  218. - numbrite formattimiseks on java.text.NumberFormat klass; tolle konstruktorit otse ei kutsu,
  219. vaid kasutad getInstance meetodit, millel on mitmeid overload'e (java.util.Locale,
  220. DecimalFormat, jne)
  221. - kui teed sellest instantsi, siis nt .format meetod formaadib numbrid sinu lokaali;
  222. - samal objektil on ka parse meetodid;
  223. - parse meetod returnib java.lang.Number instantsi, mis on Interger, Long jt klasside
  224. parentiks;
  225. - Math:
  226. - palju funktsioone (sin, asin, exp, log, max, min etc söövad parameetrina double'it; prolly on overloaditud tho);
  227. - Date:
  228. - manipuleerimiseks on java.util.Calendar, aegadega töötamiseks aga java.util.Date
  229. - paljud Date'i meetodid on deprecated, nt getDate, getMonth... selle aseme tuleks Calendar
  230. klassi meetodeid kasutada;
  231. - date parsing ja formatting tuleb java.text.DateFormat ja java.text.SimpleDateFormat klasside läbi;
  232. - DateFormat on getInstace meetoditega; SimpleDateFormat on DateFormati enda implementatisoon,
  233. mis on lithsalt lihtsam kasutada.
  234. - DateFormat - supports styles and patterns;
  235. - DateFormat df = DateFOrmat.getDateInstance(DateFormat.MEDIUM)
  236. - df.format(Date objekt) -> formattib Date vastavalt df-i formaadile;
  237. - df.parse(String date) -> stringi formaat peab vastama loodud DateFormat objekti formaadile;
  238. - leniency - whether of not a strict rule is applied at parsing; for isntance, if a DateFormat
  239. is lenient, it will accept string 'Jan 32, 2011, although it does not exist; it'll convert it
  240. to Feb 1, 2011 instead; if it isn't lenient, it won't accept dates that don't exist;
  241. - isLenient (bool) and setLenient(bool) saab küsida ja seada, kas DateFormat objekt on lenient;
  242. - (fyi: leniency - quality of mercy and forgiveness);
  243. - SimpleDateFormat on võimekam kui DateFormat, sest format objekti loomiseks saab
  244. vabamalt MM dd yyy etc mustreid ette anda, mitte ei pea .SHORT, .MEDIUM et al kasutama;
  245. -
  246. + Interface ning abstract class
  247.  
  248. - all i/f members are implicitly public;
  249. - implementeeriv klass peab enda signatuuris kasutama 'implements InterfceNimi'
  250. - sarnaselt parent-child suhtele: an instance of the class is also an instance of the i/f; seega
  251. if (implementeerivaKlassiObjekt instanceof Interface) // evaluates to true
  252. - i/f can extend another i/f;
  253. - subinterfaces and superinterfaces;
  254. - fields in an i/f must be initialized and are implicitly public, static and final; (ning uppercase ofc)
  255. - all methods in an i/f are implicitly public and abstract;
  256. - BUT: methods in i/f must not be declared static, since static methods cannot be abstract!!!!!!
  257. - et kõik i/f-s defineeritud meetodid peavad implementeeritud saama, siis on suuretele i/f-dele
  258. hea teha generic/base class, mis selle töö ära teeb. õige implementeeriv klass siis extendib seda
  259. ning override'ib meid huvitavad meetodid;
  260.  
  261. - abstract classes are similar to i/f-s, but all methods don't require to be overriden;
  262. - abstraktse klassi ja meetodi loomiseks kasuta lihtsalt abstract keywordi, st
  263. public abstract class DefaultMinuKlass {....
  264. - abstract klassis olevad non-abstract meetodid omavad body, seega implementatsiooni;
  265. - abstract meetodid on aga samuti lihtsalt deklaratsioonid ning need tuleb seega override'ida;
  266. - implementeeriv klass on lihtsalt klass, mis pärib abstrakse klassi ning implementeerib
  267. seal päritavas klassis deklareeritud abstract meetodit;
  268. -
  269. - (ei tea miks, aga) you should never cast to an abstract class!;
  270.  
  271. + Enums
  272. - can be part of a class or declared outside as public enum MinuEnumType { ...
  273. - using an enum is similar to using a class or an i/f, nt public MinuEnumType yksEnum;
  274. - using value in an enum is like using a class's static member;
  275. - erineb static final fieldidest selle poolest, et enumile saab väärtuseks määrata vaid
  276. enumis endas defineeritud väärtusi; ühtlasi käitub enum nagu objekt, seega saab muu
  277. hulgas kasutada Map key'd.
  278. - (in general - enumid on ohutumad kui static finals)
  279. - for loopiga itereerimiseks on .values() method;
  280. - switchimisel ei tohi case XXX prefixida enumi tüübiga; piisab vaid väärtustest.
  281. - klassi alla kuuluva enum fieldile väärtuse andmine: klassiInstants.enumField = MinuEnumType.ENUMVÄÄRTUS;
  282. -
  283.  
  284. + Collections FW (btw, nii List kui Set .add() meetod vist returnib booleani)
  285. - collection is an object that groups other objects. analoogne on generics, mida
  286. käsitleb järgmine teema.
  287. - kui millestki on unsychronized ja synchronized implementatsioon olemas, tuleks valida
  288. unsynchronized, kuna perform tollele parem; synchronized implementatsiooni kasutamist
  289. kaaluda vaid multi-threaded environmentide puhul;
  290. - aga multi-threaded envis saab ka ise synchronize'ida.
  291. - List is the most popular subinterface of Collection, and ArrayList is most popular
  292. implementation of List.(sarnaseks Listi implementatsiooniks on ka Vector, kuid
  293. see on synchronized, seega aeglasem)
  294. - üldiselt lood: List myList = new ArrayList();
  295. - for loopiga itereerimiseks: for (Object object : myList) {...
  296. - palju meetodeid... remove, add, set, indexOf, lastIndexOf...
  297. - Arrays klassil on asList meetod, mis lubab mitu elemeti korraga List'i lisada
  298. - Collection objekti itereerimiseks on kas Iterator või lihtsalt for loop;
  299. - Collection extendib Iterable, milles on iterator meetod; see meetod returnib
  300. java.util.Iterator, mida kasutades saab Collectioni objekti itereerida;
  301. - Iterator i/f omab meetodeid nagu hasNext, next, remove et al. nende meetodite
  302. aluseks on Iteratoris olev internal pointer, mis järgmise elemendile
  303. pointib.
  304. - põmst kui for'iga itereerid, siis kompileerija tasandil tõlgitakse see ikkagi
  305. List-ist tulevaks iterator objektis, millel rakendatakse for loopis
  306. .hasNext() meetodit for'i expressionis, lihtsal kujul olekski
  307. for (Object object : myList) {.... kuna Collection extendib Iterable'it.
  308. - List lubab lisada NULL väärtust, Set mitte.
  309.  
  310. - set represents a mathematical set; unlike List, Set doesn't allow duplicates nor
  311. null values;
  312. - ! siiski! some implementations of Set allow at most one null element, e.g.
  313. HashSet
  314. - setidest tulekski eelistada HashSeti, sest see on kiirem kui Set, TreeSet ja LinkedHashSet;
  315. - Queue extens Collection by adding methods that support the ordering of elemetns
  316. in a FIFO basis;
  317. - Queuel hulka meetodeid, nagu add, offer, remove, poll, element, peek,,,
  318. - java.util.Stack behaves in a last-in-first-out (LIFO) manner;
  319. - Collectioni implementatsioonidel on tavaliselt ka konstruktorid, mis collection
  320. conversionit toetavad, nt public ArrayList(Collection c)
  321. - Map hold key to value mappings (dictionary vist)
  322. - cannot be duplicate keys;
  323. - adding pairs through .put method
  324. - .remove(key) to remove
  325. - .clear to remove all mappings
  326. - .size, isEmpty
  327. - value saad kätte .get(key)
  328. - .keyset - returns a Set containing all keys in teh Map
  329. - values - ...all values....
  330. - entrySet - returns Set containing Map.Entry objects, each representing a
  331. key/value pair. the Map.Entry i/f provides getKey method that returns the key
  332. part and the getValue which returns value;
  333. - several implementations of Map
  334. - most commonly used are HashMap and Hashtable (unsynchronized and synchronised
  335. accordingly);
  336. - Map map = new HashMap();
  337. map.put("1", "one");
  338. map.size(), map.get("1");
  339. Set keys = map.keySet();
  340. - objects are made comparable and sortable with java.lang.Comparable and
  341. java.util.Comparator i/f-s
  342. - Arrays.sort has a contract with itself and objects in a need of sorting;
  343. contract in a form of java.lang.Comaprable i/f;
  344. - objects needed to compare shall implement Comaprable;
  345. - (ehk compareTo() meetodi peab ise oma klassis ikkagi implementeerima)
  346. - kui compare on implementeeritud, siis saab ka Arrays.sort meetodit kasutada,
  347. mis kutsubki compareTo-d välja;
  348. - java.lang.String, java.util.Date, pirimitiivide wrapperklassid et al
  349. implementeerivad kõik java.lang.Comparable'i;
  350.  
  351. - et sortida teiste omaduste põhjal, tuleb teha tolle klassi omaduse jaoks uus klass, mis
  352. implementeerib Comparator i/f-i; tolle omaduse põhjal sortimiseks tuleks siis callida:
  353. Arrays.sort(objektideList, new SoovitudOmaduseComparator());
  354. - kokkuvõte: java.util.Collection i/f-il on 3 sub-i/f-i: List, Set, Queue;
  355. - dictionary analoogiks on Map i/f, mille peamised implementatsioonid on HashMap
  356. ning Hashtable (millest esimene on kiirem, sest on unsynchronized)
  357.  
  358. + Generics
  359. - generics on üsna sarnane olemuselt collections freameworkile, kuid mõne suure
  360. eelisega. nt oli coll frame'il see jama, et igast get/set meetodid returnisid
  361. Object type'i, mida pidid ise downcastima, et saada õige type; generics puhul
  362. seda pole
  363. - generic type can accept parameters; that's why it's called a parameterized type.
  364. - passing different lists of type vars to a generic type result in different types,
  365. meaning List<Object> refers to different type of object than List<String>;
  366. - see on probleemiks, kui meetod ootab vaid ühte tüüpi Listi; lahenduseks
  367. '?' wildcard: public static void minuMeetod(List<?> var) { }
  368. - analoogne probleem tekib, kui on vaja määrata aktsepteeritavate tüüpide piire;
  369. selle jaoks on upper bound definition:
  370. List<? extends Number> - sööb kõiki tüüpe, mis on Numberi subclassid
  371. (Number type ise kaasa arvatud loomulikult)
  372. ehk GenericType<? extends upperBoundType>
  373. - küll vähekasutatav, kuid saab ka lower classi defienerida super keywordiga:
  374. List<? super Integer>
  375.  
  376. - legend of type variables:
  377. - E = type variable, st vairable that will be replaced by a type;
  378. used extensively by teh Collections framework);
  379. - K = map keys
  380. - V = map values
  381. - e.g. public interface Map<K, V>
  382. - T = type;
  383. - N = number
  384. - S,U,V etc - 2nd, 3rd, 4th types
  385. - generic type'ide kirjutamine on analoogne tavaliste type'ide loomisele:
  386. public class MinuGeneric<T> {.....
  387. - By convention, a type variable name consists of
  388. a single uppercase letter. (antud näites T siis)
  389. - A generic type used without parameters is called a raw
  390. type. see on backward compatibility jaoks; listist pullides on siis vaja down-
  391. castida.
  392.  
  393. + IO
  394. - java.nio.file.Files on sobilik vaid väikeste failidega töötamiseks; suuremamahuliste
  395. failide jaoks on vaja juba streame kasutada (nt InputStream, OutputStream, Reader,
  396. Writer)
  397. - java.io.File on deprecated; java.nio.file.Path interface vahetas välja.
  398. - meetoditeks nt .getName(indx), getParent, getFileName, getRoot
  399. - Path klassiga füüsiliselt midagi ei loo; selleks on vaja Files klassi;
  400. - java.nio.file.Files
  401. - createFile(),
  402. - delete(Path path) -nii symlinkidele, failidele, diridele... dir peab olema tühi;
  403. deleteIfExists(Path filepath); endiselt - kui dir pole tühi, siis saad
  404. DirectoryNotEmptyException'i
  405. - et diris olevate elementide üle itereerida, on olemas Files klassi kuuluv
  406. newDirectoryStream() meetod;
  407. directorysteram returned must be closed after use. (miks ei tea???)
  408. - copying:
  409. copy; CopyOption (java.nio.file interface); StandartCopyOption enum on CopyOptioni
  410. üheks implementatsiooniks.
  411. - move()
  412. - reading-writing:
  413. readAllBytes(), readAllLines...
  414. write() on overloaditud nii stringide kui byte'ide jaoks; lisaks Pathile saab
  415. kaasa anda optional OpenOption ja Charseti overloadi; OpenOptioniks annad kaasa
  416. enum'i, nagu nt APPEND, CREATE, READ, SYNC, WRITE et al;
  417. - io streams
  418. (peamiselt kasut. Files.newinputStream & newOutputStream)
  419. - söödava data sortsu kutsutakse sink-iks; võib olla nt file, ntw socket või mem;
  420. - nagu write ja readAllLines puhul, on ka streamil omad abstract klassid nii
  421. characteride töötlemiseks (Reader ja Writer) kui ka binary data töötlemiseks
  422. (InputStream, OutputStream);
  423. - streamid teeb eriti heaks see, et source/dest pole oluline(kas fail v ntw näiteks);
  424. et konkreetsesse sinki ühenduda, siis pead lihtsalt vastava implementatsiooni-
  425. klassi ehitama;
  426. - output:
  427. - sarnaselt InputStreamile 3 overload meetodit: write(int b), write(byte[] data),
  428. write(byte[] data, int offset, int length)
  429. - on ka close ja flush meetodid; viimane forces any buffered content to be written
  430. out to the sink.
  431. - characterite kirjutamiseks on Writer abstract class.
  432.  
  433. - Writer klass: sarnane OutputSreamile, aga tegeleb byte'ide asemel charidega;
  434. samuti 3 metod overloadi, write(int b), write(char[] text), write(char[] text,
  435. int offset, int length)
  436. - stringe aktsepteerivad write(String text), write(String text, int offset, int len);
  437. - kui õigesti mõistan, siis charide kirjutamiseks ongi esmalt vaja luua OutputStream
  438. (OutputStream os = Files.newOutputStream(path, openOption);
  439. ja seejärel OutputStreamWriter:
  440. OutputStreamWriter writer = new OutputStreamWriter(os, charset);
  441.  
  442. - OutputStreamist on parem PrintWriter, sest tollel on method overloadid, mis
  443. võimaldavad suva java primitiive ja objekte otse faili kirjutada;
  444. - (ehk sitaks print ja println overloade sõltuvalt parameetri tüübist)
  445. - kuna PrintWriterit ei saa BufferedWriterisse wrappida, tuleks hoopis
  446. wrappida Writer, mis on PrintWriteri argumendiks;
  447. - (ehk kui õigesti mõistan, siis Writeri wrapid BufferedWriteri sisse, ning
  448. selle Writeri instantsi annad PrintWriteri loomisel argumendiks);
  449. - to read chars, you use Reader class;
  450. - logimiseks on hea PrintStream klass (lolei, Apache log4j on teh shite logimiseks);
  451. - System objekt lubab default PrintStreami asendada setOut meetodiga (System.out
  452. on a type of java.io.PrintStream, seega saad selle out'i mingi enda PrintSreamiga
  453. asendada, nt logid otse faili)
  454. - streamid on siis head, kui on vaja faili datat järjest kasutada (hence stream, st
  455. data jooksebki sisse/välja streamina) või nt network socketiga töötada; kui on aga
  456. tarvis muuta nt 1000ndat bitti igast failist, on mõistlikum kasutada
  457. java.nio.channels.SeekableByteChannel interface'i (enne jdk7-t kasutati
  458. java.io.RandomAccessFile klassi, kuid nüüdkseks on see deprecated);
  459. - SeekableByteChannel teostab nii readi kui write'i
  460. - SBC-ga lugemiseks või kirjutamiseks on lihtsalt vastavalt read() ja write()
  461. meetodid, mis võtavad parameetriks java.nio.ByteBuffer. = java.nio.Buffer
  462. üheks alamklassiks; nagu nimi ütleb, bufferdab byte'e.
  463. - ByteBuffer omab mitmeid put ja get meetodeid (eri datatüüpidele, offset, length
  464. jms võimalsued)
  465. - loomiseks kasuta .allocate meetodit (ByteBuffer bf = ByteBuffer.allocate(12);
  466. -
  467. - objekti state'i saab salvestata object serializationi läbi; selleks on nt
  468. ObjectOutputStream. konkreetse state'i retrieve'imiseks nimetatakse deserializationit,
  469. mida saavutatakse ObjectInputStreami läbi;
  470. - et objekt oleks serialiseeritav, peab ta implementeerima java.io.Serializable
  471. interface'i;
  472. - serialization is based on last in first out (LIFO);
  473. -
  474. - Nested & inner classes:
  475. - 2 types of nested classes: static inner classes and non-static nested casses;
  476. - non-static nested classes are called inner classes;
  477. - (static nested klasse saad luua ilma top-level klassi instantsieerides,
  478. kasutades OuterClassName.InnerClassName formaati;
  479. inner classi puhul saad initsieerida inner classi vaid läbi välimise klassi
  480. instantsi);
  481. - to top-lvl class, a nested class is just like other class members, e.g. methods
  482. and fields; nested class can have one of the four access modifiers, whereas a
  483. top lvl class can only have eithter public or default (vist package?);
  484. - inner classi instantsi saab luua läbi toplevel klassi instantsi kaudu:
  485. TopLevel toplvl = new TopLevel();
  486. TopLevel.Inner inner = toplvl.new Inner();
  487. - local inner class (or local class for short) = inner class that by definition is NOT
  488. a member class of any other class (sest declaration ei ole otse outer classi deklaratsioonis)
  489. - LC on defineeritav igasuguses code blockis ning tolle skoop langebki puhtalt
  490. sinna blocki (think if, while blocks etcetc);
  491. - LC on nt siis mõistlik, kui implementeerib mingit i/f-i ning seda implementatsiooni
  492. ei kasutata mujal kui konkreetses meetodis (kus LC on defineeritud);
  493. - Not only does a local class
  494. have access to the members of its outer class, it also has
  495. access to the local variables. However, you can only
  496. access final local variables. The compiler will generate a
  497. compile error if you try to access a local variable that is not
  498. final.
  499. - anonymous inner class:
  500. - enamasti i/f-ide implementeerimiseks; neil pole oma nime. nt on selline i/f
  501. nagu Printable; kuskil mujal klassis implementeerid seda anon klassiga:
  502. Printable minuPritner = new Printable () { implemeneerid ,};
  503. - pane tähele, et closing brace'i lõpus on semikoolon!; also, põmst toimib
  504. magic läbi 'new' keywordi;
  505. - anon inner klassi saab luua ka extendides abstract või concrete klassi;
  506.  
  507. + swing & AWT
  508. - awt kasutab OSi native apit, et joonistada GUId, swing aga teeb kõike ise;
  509. java.awt core'iks on Component class;
  510. - Swing kasutab siiski AWT event modelit;
  511. - all swing components except JFrame, JDialog and JApplet reside in containers;
  512. JDialog is like a JFrame, but normally resides within a JFrame or another JDialog;
  513. - swingi komponentide eristamiseks AWT omadest prefixitakse need J-ga;
  514. -
  515. - (swingis palju asju... loe dokist lol)
  516. - default layout on BorderLayout (see N-S-W-E-center)
  517. -
  518.  
  519. + java event model;
  520. - event is encapsulated in an envent object; there are 3 participants:
  521. - event source, which is the object whose state changes;
  522. - event object, ehich encapsulates state changes in the event source;
  523. - event listener, which is the object that wants to be notified of state changes in
  524. the event source;
  525. - ehk: when event occurs, the event source generates an event object and
  526. sends it to the event listener;
  527.  
  528. + Polymorphism
  529. - A a = new b B;
  530. - a on complile ajal type A, aga runtime'il type B!
  531. - JVM otsustab runtime'il millist meetodit kasutada, ehk method calli ning
  532. method blocki bindimine toimub runtime'il, mitte compiletime'il; seda
  533. nimetatakse late bindinguks;
  534. - polym doesn't work with static and final methods (sest static methods are early-
  535. bound ning final meetodeid ei saa extendida);
  536.  
  537. + Annotations (need @Deprecated, @AnnotationType(elementValuePairs) et al;
  538. - annotation type is a special interface type;
  539. - annotation is an instance of an annotation type;
  540. - they're in form of key-value pairs;
  541. - annotation types w/ no key/value pairs are called marker annotations;
  542. - annotation w/ one pair are ofter referred to single-value annotation types;
  543. - common annotations - mingi standardi järgi defineeritud annotatsioonid, nagu
  544. Generated.
  545. - meta-annotations - annotations that annotate annotations:
  546. - Documented
  547. - Javadoci vms kasutades dokumenteeritakse @Documented annotatsiooniga
  548. annoteeritud annotatsioonid (nt @Drprecated dokumenteeritakse seetõttu);
  549. - Inherited
  550. - sellega annoteeritud klassi sub-klassid pärivad parenti annotatsioonid;
  551. - Retention
  552. - näitab kaua @Retention-iga annoteeritud annotatsioone tuleks alles hoida;
  553. value'ks 1 kolmest enumist: SOURCE, CLASS, RUNTIME
  554. - Target
  555. - defineerib millised programmi element/did võivad saada annoteeritud selle
  556. metaga annoteeritud annotatsioonide instantside poolt;
  557. sellel samuti mitu enumi väärtusteks (raamatus lk 577);
  558. - enda annotatsiooni defineerimine on täpselt nagu interface'igi, ainult et @ märk
  559. on ees: public @interface MinuAnnotation { ... }
  560. -
  561.  
  562. + i19n and l10n
  563. - internationalizationi võtmeks on java.util.ResourceBundle class (abstract), mis võimaldab
  564. lihtsalt lugeda locale'i spetsiifilist properties faili; sisaldab endas getBundle
  565. staatilist meetodit mis returnib konkreetse subclassi instantsi;
  566. - sellisel juhul on properties faili nimeks:
  567. basename_langCode_countryCode (basename on ResourceBundle enda base name)
  568. nt: MyResources_en_US.properties
  569. - kui vajalikku prop faili ei leita, fallbackitakse default prop failile, milleks
  570. on basename.properties;
  571.  
  572. - value lugemiseks on getString meetod; passitakse key;
  573. - (ühesõnaga - ResourceBundle lubab mugavamalt failides sisalduvaid key-value
  574. pairidele ligi pääseda)
  575.  
  576. + Applets
  577. - Applet klass on .Panel subclass...
  578. kuna on Panel, siis saab AWT komponente lisada.; siingi on JApplet olemas;
  579. - Appletil on omajagu funktsioone, nagu init, start, stop, destory, isActive, paint,
  580. showStatus, getParameter, getCodebase, getDocumentBase, getAudioClip, play,
  581. getImage, getAppletContext etc;
  582. - AppletContext i/f
  583. - AppletContext is created by the web browser (or applet viewer for that matter);
  584. - enamus siinseid meetodeid on duplikeeritud Appletis, v.a. showDocument meetodid,
  585. millega lihtsalt kuvatakse teisi URLide dokumente, kui see, millel Applet ise
  586. asub;
  587. - AppletStub i/f
  588. - when browser creates an applet, it also creates an AppleStub object that it passes
  589. to the applet by calling the setStub method on the Applet object; this stub
  590. acts as an i/f between an applet and the browser env or applet viewer env;
  591. !kui just ise applet viewerit ei loo, siis see meid ei huvita!
  592. - appletile söödad parameetreid param tagiga html-is, nt
  593. <param name="customer" value="Jane Goddall"/>
  594. - väärtusi küsid getParameter meetodiga;
  595.  
  596. + Networking
  597. - application layer protocols (HTTP, FTP, telnet et al) use the protocols in the
  598. transport layer (e.g. TCP and UDP); transport layeri protocolid omakorda utiliseerivad
  599. neist allpool olevaid protokolle (IP);
  600. - HTTP - request-response protocol;
  601. - request consists of 3 components:
  602. - method -- uniform resource identifier (URI) -- protocol/version, e.g.
  603. POST /examples/default.jsp HTTP/1.1
  604. - request headers
  605. - contains info about client env and the body of the entity, i.e. browser
  606. lang, lenght of the entity body etc;
  607. - each header is separated by a carriage return/linefeed (CRLF) sequence;
  608. - between headers and the entity body there's a blank line (CRLF), which
  609. tells the HTTP server where the entity body begins;
  610. - entity body
  611. - response contains also 3 parts:
  612. - protocol -- status code -- description
  613. - response headers
  614. - entity body
  615.  
  616. - üldine põhimõte sama mis requestigagi; body on mõistagi HTML content;
  617. - java.net.URLConnection
  618. - represents a connection to a remote machine;
  619. - URLC class doesn't have a public constructor, so you can't construct a URLC
  620. with the 'new' keyword;
  621. - to obtain an instance, call the openConnection method on an URL oject;
  622. -
  623. - by default, on enabletud read, aga mitte write; selle jaoks on URLconnectionil
  624. 2 booleani: DoInput ja doOutput; et kirjutada, tuleb latter trueks seada:
  625. connection.setDoOutput(true);
  626. - aga! kuigi sellega saab postida message'eid, siis tavalisetlt seda
  627. selleks otstarbeks ei kasutata; selle jaoks on olemas hoopis
  628. java.net.Socket ning java.net.ServerSocket;
  629. - java.net.Socket (btw, Socket on vaid kliendipoolne)
  630. - socket is an endpoint of a network connection; socket võimaldab networki IO-d;
  631. - et saata bytestreami, tuleb esmalt callida Socketi getOutputStream meetod et
  632. obtainida java.io.OutputStream object; et saata texti, tahad pigem constructida
  633. java.io.PrintWriter objecti (OutputStream objekti kaudu ofc);
  634. - btw - socketi konstruktoris tahab hosti saada mingil põhjusel ilma protokollita;
  635. - java.net.ServerSocket
  636. - sama mis Socket (idee tasandil), kuid serveri poolne;
  637. - kui ServerSocket saab connection requesti, loob Socket instantsi et suhelda
  638. kliendiga;
  639. - the IP addy the server socket is listening on is referred to as the binding
  640. address;
  641. - another important property of a server socket is its backlog, which is the
  642. maximum queue length of incoming connection requests before the server socket
  643. starts to refuse the incoming requests;
  644. - SS paned requesti kuulama accept meetodiga; requesti püüdmisel returnib
  645. Socket objekti, mille kaudu siis IO-d teostatakse; SS vist ongi pelgalt
  646. kuulamiseks?
  647. - e: jah, SS on kuulamiseks: Socket clientSocket = ServerSpcket.accept();
  648. -
  649.  
  650. + DB
  651. - JDBC;
  652. - basically 4 types of JDBC drivers (type 1 to 4);
  653. - DB access has 4 steps:
  654. - loading the JDBC driver of the db to connect to;
  655. - obtaining a db conntection;
  656. - creating a java.sql.Statement instance that represents an SQL statement;
  657. - optionally reating a java.sql.Result to store data returned from the db;
  658. - closing JDBC objects to free resources; thanks to try-with-resources,
  659. no need to do this manually;
  660.  
  661. - java.sql.Connection i/f is template for connection objects; obtained by
  662. java.sql.DriverManager's getConnection static method; parameetriteks enamasti
  663. kas url(stringina) või siis url, username passwd;
  664. - Connection objektist tehakse Statement või PreparedStatement (viimane on precompiled);
  665. Statement stat = connectionObject.createStatement();
  666. PreparedStatement pstat = connection.prepareStatement(String sql);
  667.  
  668. mõlemaid kasutad executeQuery nin executeUpdate (erinevad signatuurid PS ning S
  669. puhul, kuna viimase puhul ei pea päringut kaasa andma, kuna on juba precompiled);
  670. - queryst tulnud tabelit esitab ResultSet;
  671. - itereerid seda next meetodiga, mis returning true v false olenevalt kas on
  672. järmine rida olemas või mitte;
  673. - data grepimiseks sitaks getXXX meetodeid, nagu geInt, getLong, getShort etc;
  674. - getXXX meetoditel tavaliselt 2 overload'i: int ja columnname;
  675. - closing:
  676. - resultSet.close();
  677. - statement.close();
  678. - connection.close();
  679.  
  680. - korrektne on aga sulgeda finally klauslis (if (resultSet != null)... etc);
  681. - java7-st alates aga try-with-resources:
  682. - try (Connection con = getConnection();
  683. Prepared pstat = connection.preparedStatement(sql);
  684. ResultSet rset = pstat.executeQuery()) {
  685. while (result.next()) {
  686. // data mainpulation
  687. }
  688. }catch (SQLException e) { .....
  689. - et saada metadatat (nr of columns in ResultSet, name on type of each column etc),
  690. siis kutsud ResultSet-ile getMetaData meetodi;
  691. - saadava ResultSetMetaData objektil mitu meetodit, nagu
  692. getColumnCount, getColumnName, getColumnType...
  693. -
  694.  
  695. + Thurds
  696. - thread is the smallest unit that can take processor time;
  697. - T is sometimes called a lightweight process or an execution context;
  698. - every java program has at least one thread; the thread that executes when you invoke
  699. the static main method;
  700. - Swing for instance has a thread for processing events in addition to the main thrd;
  701. - threadi loomiseks 2 meetodit;
  702. - extendi java.lang.Thread klassi; (enamasti tegelt Thread klassiga otse ei
  703. tegeleta);
  704. - (sellisel juhul override'itakse run() meetod, mida jooksutatakse, kui
  705. Thread objektile jooksutatakse start() meetod;)
  706. - implementeeri java.lang.Runnable i/f-i;
  707. - (siin on run meetod, mida tuleb implementeerida);
  708. - btw, Thread ise implementeeribki Runnable i/f-i;
  709.  
  710. - Runnable kasutamiseks lihtsalt implementeerid Runnabe'i run() meetodit;
  711. main() meetodis lood uue instantsi endast, ning passid selle Thread-ile:
  712. Thread minuThurd = new Thread(minuRunnableImplementeerivObjekt);
  713. - threadil võib olla nimi; lisaks on tal state, mis saab olla 1 kuuest:
  714. - new (has not been started);
  715. - runnable (thread is executing);
  716. - blocked (thread is waiting for a lock to access an object);
  717. - waiting (waiting indefinitely for other thread to perform an action);
  718. - timed_waiting (sama mis eelmine, aga ootab kindla aja);
  719. - terminated (thurd has exited);
  720. - state'id on ...Thread.State enum'is encapsulated;
  721. - thread priority
  722. - teistele threadidele tekitatakse CPU aega sleep() välja kutsumisega;
  723. - vabanenud ressursi jagamist otsustatakse prioriteetide põhjal;
  724. - prio setimiseks on setPriority(int) meetod;
  725. - kõrgem int tähedab kõrgemat priot;
  726. - kui mitu threadi kasutavad samu ressursse, võib tekkida thread interference;
  727. et seda ei oleks, tuleb kasutada locke; selle jaoks on 'synchronized' modifier;
  728. (jällegi - see pole kõige parem meetod; nii threadide loomiseks-kasutamsieks kui
  729. ka mitme threadi manageerimiseks on parem Concurrency Utilities);
  730. - igal objektil on selline asi nagu intrinsic lock;
  731. - a synchronized modifier can be used to lock an object; the intrinsic lock is
  732. released when the method, holding the synchronized modifier, returns;
  733. - üldiselt kasutatakse non-static meetoditel, kuid on võimalik rakendada ka
  734. staatilistel meetoditel, mis juhul kasutatakse Class objekti lukku, mis on
  735. associated kutsutava meetodi klassiga;
  736. - the code segmets that guarantee only one thread at a time has access to a shared
  737. resource are acalled critical sections; in java critical sections are achieved
  738. using the synchronized keyword;
  739. - eelnev kirjeldab method synchronizationit, kuid on olemas ka block synchronization,
  740. mis lukustab terve koodibloki:
  741. synchronized(objekt) {
  742. // tee midagi kuniks see objekt on kinni
  743. }
  744. - sisuliselt on tegu ikkagi sama asjaga, sest
  745. syncronized(this) { }
  746. st: Synchronizing on the method is functionally equivalent to having a
  747. synchronized (this) block around the body of the method.
  748. - kui on palju lühikese elueaga thrade, on targem kasutada thread poole; ise leiutamise
  749. asemel kasuta pigem util.concurrent pakki, which includes mutexes, semaphores,
  750. collection classes like queues and hash tables that perform well under concurrent
  751. access and several work queue implementations;
  752. - poolide ohud: deadlock, resource thrasing and complexities of wait() and
  753. notify();
  754. - fyi: üks IBM'i artikkel thurd poolidest: http://www.ibm.com/developerworks/library/j-jtp0730/
  755.  
  756.  
  757.  
  758. + Visibility
  759. - syncida tuleb ka siis, kui pole tegemist non-atomic operatsioonidega, sest multi-
  760. thurd programmides ei pruugi thread teise poolt teostatud operatsioondie tagajärgi
  761. näha (vari väärutse muutmine nt); see tuleneb java memory mudelist;
  762. - seda probleemi saab samuti synchronized asjaga parandada; kui on nt mingi var,
  763. mida üks thread loeb, teine muudab, siis lood lihtsalt 2 getter-setter meetodit,
  764. kumbki synchronized;
  765. - syncing nõuab aga overheadi, mistõttu kui mutual exclusion pole vajalik (vaid
  766. kõigest visibility), tuleks kasutada hoopis volatile keywordi;
  767. - volatile keywordi kasutad variable'i definitsioonil !!!
  768. -
  769. - thurdide coordinationi jaoks on mitmeid Object klassi meetodeid:
  770. - wait() - thread waits until another thread invokes notify or notifyAll method;
  771. - peab alati wait loopis asuma; põmst annab monitori ownershipi ära ning
  772. jääb teise threadi poolt callitavat notify() või notifyAll() ootama;
  773. - wait(long timeout) - sama mis eelmine, aga ootab kuni teine thurd saadab
  774. notify(All) VÕI timeout aeg on möödunud;
  775. - notify() - notifies a single thread that is waiting on this object's lock;
  776. kui on mitu thurdi ootamas, siis üks valitakse, kes saab teavitatud, ning
  777. see avlik on arbitraarne;
  778. - notifyAll() - kõiki ootavaid thurde teavitatakse;
  779. -
  780.  
  781. + Timers
  782. - java.util.Timer provides alternative approach to performing scheduled or recurring
  783. tasks; first create a Timer, call its schedule() method, passing a
  784. java.util.TimerTask object. The latter contains code that needs to be executed by
  785. the Timer;
  786. - TimerTask class omab run meetodit, mis tuleb override'ida; erinevalt Runnable
  787. run() meetodist, ei pea seda override'i loopi enclose'ima;
  788. - Swingil on oma timerklass: javax.swing.Timer (swingi jaoks parem, muidu veits
  789. vähem võimekam);
  790.  
  791. + Concurrency utils
  792. - parem/lihtsam kasutus thread and sychronization feature'ite kasutamiseks;
  793. - siin igast ägedad type'id (atomic package'is), nagu AtomicInteger, AtomicLong et al;
  794. nendega opereerimiseks meetodid nagu incrementAndGet, getAndIncrement jne;
  795. - kui võimalik, ära kasuta Threadi et exeda Runnable'i taski; mõislikum on kasutada
  796. java.util.concurrent.Executor või subinterface ExecutorService'it;
  797. - void execute(java.lang.Runnable task)
  798. - harva kui on tarvis endal implementeerida Executor v ExecutorService'it;
  799. pigem kasuta Executors klassis defineeritud staatilisi meetodeid: (kõik returnivad
  800. ExecutorService'i)
  801. - newSingleThreadExecutor()
  802. - newCacheThreadPool()
  803. - see loob ise rohkem threade, kui rohkem taske submittitakse;
  804. - newFixedThreadPool(int numOfThreads)
  805. - Runnable taske söödad Executorile ette nii:(kui lühike task, siis defineerigi
  806. anonüümselt nagu siin; kui aga pikem või vajab inputi, siis tee eraldi klass):
  807.  
  808. Executor executor = Executors.newSingleThreadExecutor();
  809. executor.execute(new Runnable() {
  810. @Override
  811. public void run() {
  812. // do something
  813. }
  814. });
  815.  
  816. - Callable is a task that returns a value (and may throw an exception);
  817. is similar ot Runnable, except that the latter cannot return a value nor throw an
  818. exception;
  819. - Callable defines a method, call:
  820. - V call() throws java.lang.Exception
  821. - põmst enda class lihtsalt implementeerib Callable'i, kus sees on call() override,
  822. mis returnib väärtust;
  823. - Callable (i/f) can be passed to an ExecutorService's submit method:
  824. - (ehk praktikas söödad ExecutorService instansi submit meetodile
  825. Callable i/f-i implementeeriva klassi intantsi ette)
  826. - Future<V> result = executorService.submit(callable);
  827. - the submit() mehtod returns a Future, which can be used to cancel the task or
  828. retrieve the return value of the Callable; to cancel a task, call the cancel
  829. method on the Future object:
  830. boolean cancel(boolean myInterruptIfRunning)
  831. (passing false allows an in-progress task to complete undistrubed; true
  832. cancels immediately);
  833. - to get a result from Callable, call get() method of corresponding Future:
  834. V get()
  835. blocks until task is complete;
  836. V get(long timeout, TimeUnit unit)
  837. waits until a specified time lapses;
  838. - to find if task has been cancelled or complete, call Future's isCancelled or
  839. isDone method;
  840. - lõpetamisel tuleb ExecutorService lõpetada: executorService.shutdownNow();
  841.  
  842. + Swing Worker
  843. - javax.swing.SwingWorker abstract class is an utility class that helps you with
  844. time-consuming tasks in a Swing application; after you instantiate a subclass of
  845. SW, you can call its execute() method to start the worker. Calling execute in turn
  846. invokes the doInBackground method on a different thread; you should write your
  847. code in this method;
  848. - point selles, et swingis muidu käitab GUI-d ning eventhandlereid 1 thread;
  849. kui mingi event võtaks sitaks aega, muutuks GUI unresponsive'iks;
  850. - intermediate datat saab publishida publish() meetodiga; iga kord kui seda meetodit
  851. callitakse, invoke'ib SW process() meeotdi;
  852. - on ka done() ja cancel() meetodid;
  853. - (põmst siin ongi oluline publish meetodi kasutamine, process() meetodi overridemine;
  854. ei saa sellest päris täpselt aru; publishi parameetriks tulebki vist list... panna?
  855. ning processil argumentideks mingi... teadmata arv elemente vastu võtta? (stiilis
  856. process(Integer... chunks) { ... } ? dunno lol
  857.  
  858. + Lock i/f pakub meetodeid synchronized limitatsioonidele (nagu nt see, et ressurssi
  859. ei saa vabastada muust meetodist, kui sellest mis lukustas; limiteeritud vaid
  860. meetoditele ning blokkidele;)
  861. - Lock tuleb nii lock kui unlock meetoditega;
  862. - hea tava on unlock'i kutsuda finally klauslis;
  863. - on veel tryLock(), tryLock(long time, TimeUnit timeUnit)
  864. (returns true, if lock available; kui false, siis ei blocki!);
  865.  
  866. + Security
  867. - et java application oleks ohutu(m), tuleb teda jooksutada security manageriga;
  868. - the way to tell the SM what permissions are allowed is by passing a policy file;
  869. - To run a Java application with the security manager, invoke
  870. the java program with a −D flag.
  871. java -Djava.security.manager MyClass arguments
  872. - Here is the syntax for passing a policy file to the java tool.
  873. java -Djava.security.manager -Djava.security.policy=policyFile MyClass arguments
  874. - if no policy file is specified then default is used (mingi system security properties
  875. file - java.security);
  876. - policy failis on grant ning keystore entried;
  877. - grant - entry includes one or more permission entries, preceded by optional codeBase,
  878. signedBy and principal name-value paris.
  879. - principal value specifies a className/principalName pair which must be
  880. present within the executing threads principal set [wut lol ???];
  881. - grant entry consists of one or more permission entry;
  882. - permission entry syntax: permission permissionClassName target action
  883. - policyt saad defineerida kas lihtsalt txt failis või policy tooliga;
  884. - appletitele lisaõigusi saamiseks tuleb signida (JarSigner Tool)
  885. -
  886. - SSL certificate contains the following:
  887. - a public key;
  888. - information about the subject, ie. the owner of the public key;
  889. - the certificate issuer's name;
  890. - some timestamp to make the certificate expire after a certain period of time;
  891.  
  892. - et kontrollida kas dokument on originaalsel kujul:
  893. - decrypt the digest accompanying the doc using the signer's public key;
  894. - create a digest of the doc;
  895. - compare them (they need to match);
  896.  
  897. - FYI: digest takes a plain text and generates a hashcode which can be
  898. used to verify if the plain text is unmodified but wich CANNOT be used
  899. to decrypt the original text form the hash value
  900. (ehk siis lihtsalt hash/checksum)
  901. - To apply for a certificate, Bob
  902. has to generate a pair of keys and send his public key to a
  903. certificate issuer, who would later authenticate Bob by
  904. asking him to send a copy of his passport or other types of
  905. identification. Having verified Bob, a certificate issuer will
  906. sign the certificate using its private key. By ‘signing’ it
  907. means encrypting. Therefore, the certificate can only be
  908. read by using the certificate issuer's public key.
  909. - nüüd jagab Bob public key asemel sertifikaati;
  910. - saadud certe on samuti mõistlik hoida keystore'is
  911. keytool -importcert -alias minuAlias -file certMidaImpordin.cer
  912. -
  913.  
  914. + java web applications
  915. - põmst on Servlet i/f contractiks servleti ning containeri vahel;
  916. - there are 3 official technologies for web dev:
  917. - servlet (core tech, millele teised toetuvad)
  918. - javaserver pgaes (JSP)
  919. - javaServer Faces (JSF)
  920. - a servlet application runs inside a servlet container, aka servlet engine;
  921. - a servlet/JSP (need käivad koos) container is a special web server that can process
  922. servlets as well as serve static contents;
  923. - Apache Tomcat and Jetty are the most popular servlet/JSP containers that are free
  924. and open-source.
  925. - Servlet and JSP are of Java EE tehcs (nagu on ka JMS, Enterprise JavaBeans (EJB),
  926. JSF, Java persistence..);
  927. - java EE appi jooksutamiseks on tarvis Java EE containerit, aga piisab ka
  928. servlet/JSP containerist;
  929. - (nt Tomcat ongi servlet containeriks);
  930. -
  931. - all servlets must implement javax.servlet.Servlet;
  932. - init, service & destroy are life cycle methods;
  933. - init: container invoke'ib first time the servlet is requested (hiljem mitte);
  934. - service: iga kord kui servlet on requestitud;
  935. - destroy: siis kui application is unloaded or container is being shut down;
  936. cleanup code läheb siia;
  937. - thread safety! container creates an instance of a servlet which is shared among
  938. all users, so class-level vars are not recommended, unless they are read-only
  939. or atomic vars;
  940. - nagu tavaks, pole ka siinkohal vist kõige mõistlikum Servlet-it ennast otse
  941. implementeerida; lihtsam on extendida nt GenericServlet'it või HttpServlet-it;
  942. -
  943. - failid asuvad kindlas dir-struktuuris (WEB-INF->classes/lib)
  944. - muud ressursid (pildid, HTMLs) organiseerid application diri (mis asub classes
  945. all);
  946. - deployimiseks paar võimalust:
  947. - kõige lebom on applicationi dir kogu pasaga kopeerida webapps diri Tomcati
  948. installatsioonis;
  949. - alternatiivina võib deployida ka .war failina (mis on sama mis jar, aga war
  950. extensioniga lol);
  951. - pärast loomist kopeeri war webapps diri, restarti Tomcat, ning ta pakib
  952. war-i automaatselt lahti;
  953. - veel on võimalus editida server.xml faili Tomcati conf/ diris või deployida
  954. spetsjomm XML fail;
  955. - invoke'imiseks: http:/localhost:8080/projekt/url-mis-sai-annotatsioonis-nimetatud
  956. - iga HTTP requesti jaoks loob servlet container ServletRequesti instantsi, mis
  957. encapsulate'ib requesti info ning passib selle servleti service meetodile;
  958. - ServletRequestil mitmeid meetodeid, millest kasutatavaim ehk getParameter
  959. (lisaks getParameterNames, getParameterMap, getParameterValues);
  960. - service meetodile antakse kaasa ka ServletResponse, mis peidab ära browserile
  961. vastuse saatmise keerukuse;
  962. - ServletResponse'i oulisim meetod on getWriter method, mis returnib
  963. java.io.PrintWriter objekti;
  964. - üldiselt vastad HTML-ina; enne HTML tagide saatmist oleks hea kutsuda
  965. setContentTYpe, passides "text/html" argumendina; (mõned browserid võivad ilma
  966. content type'i täpsustamata interpreteerida seda plain textina);
  967. - every piece of info for the ServletConfig object is called an initial parameter;
  968. initial param has 2 components: key and value;
  969. initial params are passed to a servlet by using an attribute @WebServlet or by
  970. declaring it in a configuration file called the deployment descriptor;
  971. - to retrieve initial param from within servlet, call getInitParameter on the
  972. ServletConfig; või getInitParameterNames (returnib stringi asemel
  973. enumerationi);
  974. - getServletContext - returnibki ServletContexti
  975. - represents servlet application; there's only one context per web application;
  976. - kui on distributed env ning sama app on deployitud mitmel konteineril, siis
  977. on üks ServletContext per JVM;
  978. - asja point on jagada common infot ressursside vahel applicationis ning
  979. to enable dynamic registartion of web objects (done by sorting objects
  980. in an internal Map within ServletContext); objects stored in SC are
  981. called attributes, and objects stored here can be accessed by any servlets
  982. in the application.
  983. - otse Servlet-it implementeerimise asemel on mõistlikum extendida GenericServlet
  984. abstract klassi, mis:
  985. - assignib ServletConfig objekti class lvl variks, mille saab getServletConfig
  986. - provideb default implemetnatsioonid Servleti i/f meetoditele;
  987.  
  988. - overridida tuleb no-arg init() (kui on vaja sinna midagi üldse lisada, sest
  989. ServletConfig nagunii talletatakse ju class-lvl vari);
  990. -
  991.  
  992. + HTTP servlets
  993. - enamasti töötad just nendega lol;
  994. - HTTP servlet class overrides GenericServlet (seega peaks abstract class olema)
  995. - service meetodide asemel override'id doGet() ja/või doPost() meetodeid (veel on
  996. 5 meetodit, mida kasutab harvem);
  997. - ServletRequest ja -Response'i asemel töötab HttpServletReq ja resp-iga;
  998. - ühe asjana on deploymenti juures tarvis mappida servlet pathiga; enne teostasime
  999. seda WebServlet annotation type'iga; teine võimalus on kasutada deployment des-
  1000. criptorit;
  1001. - the descriptor must be named web.xml and saved in the WEB-INF dir of the
  1002. application;
  1003. - deployment descriptor allows to override values specified in a servlet annotation;
  1004.  
  1005. + JavaServer Pages (JSP)
  1006. - servletitega see jama: HTTP vastus HTML-i näol on Stringidena; teiseks - HTML
  1007. tagid on hardcoded;
  1008. - JSP päästab; btw, jsp ei asenda Servleti, vaid lisab väärtust. Java web appid
  1009. kasutavadki korraga nii servleteid kui ka JSP-d;
  1010. - JSP page is essentially a servlet;
  1011. - JSP pages are basically text files w/ jsp extension;
  1012. - JSP pages run on a JSP container; a servlet container is normally aslo a JSP cont;
  1013. - kui JSP page is requested, then container does 2 things:
  1014. - translate JPS page into a JSP page inplementation class, which must implement
  1015. the Servlet i/f (result is dependent on the JSP container);
  1016. - if successful, JPS container compiles the implemetnation class and then loads
  1017. and instantiate it and perform the normal lifecycle operations it does
  1018. for a servlet;
  1019. - kui tuleb uus JSP req ning JSP page pole modifitseeritud, siis ei toimu recompilationi;
  1020. - et algest laadimisest üle olla, confi application nii et kõiki JSP page'e callitakse
  1021. kohe alguses, või precompile'i JSP page'id ning deploy them as servlets;
  1022. - JSP page contains template and syntactic elements;
  1023. - nt <% ning %> on elemendid, sest tähistavad Java code blocki algust ja lõppu;
  1024. - JSP ei pea registreeritud olema deployment descriptoris;
  1025. - .jsp failid lihtsalt projekti kausta (samas kus asub ka WEB-INF dir);
  1026. - .jsp failide lisamisel pole tarvis tomcati resada;
  1027. - kui servletis olid init, service, destroy, siis JSP-s:
  1028. - jspInit - sarnane init-ile; (see aga ei võta argumenti);
  1029. - jspDestroy
  1030. - jooksutatakse vist siis kui container (eg Tomcat) maha tapetakse?
  1031. - meetodi definitsioon: <%! ning %>
  1032. - Implicit Objects:
  1033. - Servlet-is saad service meetodiga HttpServletReq ja Resp objektid, samuti ka
  1034. ServerConfig ning ServletContext ning HttpSession objektid (viimase getSession
  1035. meetodiga); JSP-s saad neid objkte JSP implicit objektiga; nt request implicit
  1036. objekt esindab HttpServletReques objekti; seda võid kasutada justkui oleks see
  1037. referents HttpServletRequest objktile; out on JspWriter objekti referents, mis
  1038. on u sama mis PrintWriter mis tuleb getWriter meetodiga HttpServletResponse'i
  1039. objektist. nt out.println("welcome to jsp page yo");
  1040. - JSP syntax:
  1041. - directives
  1042. - scripting elements
  1043. - actions
  1044. - Directives
  1045. syntax: <%@<directive_name> ....%>
  1046. - instuctions for the jsp translator on how a jsp page should be translated into
  1047. a servlet implementation class; nendeks on taglib, tag, attribute, variable
  1048. ning 2 kõige olulisemat page and include;
  1049. - page
  1050. translatorile saab antud JSP kohta info anda, nt bufferi suurus, mida out
  1051. implicit objektiga kasutada, mis content type'i kasutada, mis java type'i
  1052. importida jne;
  1053. - include
  1054. to include the content of another file in the current JPS page; (JSP page
  1055. code reuse'i jaoks vist, kui tõmbad mingit väga kasutatavat html osa nt
  1056. sisse);
  1057. - Scripting Elements
  1058. to insert Java code into JSP page; 3 types of elements: scriptlets, declarations
  1059. and expressions.
  1060. - scriptlets
  1061. block of java code within <% %> tags; variables defined in one block is
  1062. visible to another below;
  1063. - expressions
  1064. is evaluated and its result is fed to the print method of the out implicit
  1065. object; <%= %>
  1066. ehk ei midagi muud, kui shortcut out-i söötmisel; btw, expressioni lõpus
  1067. pole semikoolonit;
  1068. - declarations
  1069. <%! %>
  1070. lihtsalt declare'id variable ning meetodeid mida saab JSP lehel kasutada;
  1071. - error handling: try block toetatud; hea on teha error leht, kasutades isErrorPage
  1072. attribute'i page direktiivis; teised lehed kasutavad seda lehte läbi errorPage
  1073. attribute'i page direktiivis;
  1074.  
  1075. + Javadoc
  1076. - javadoc loob HTML faile mis kirjeldab kas package'it või type'i;
  1077. - you can write doc comments for a class, an i/f, a method, constructor, and a field;
  1078. - tags: @tag or inline tag: {@tag}
  1079. - tage on sitaks yo
  1080. - javadoc on põhiproge, kuid on võimalik vist eristada doclet'it mis reaalselt
  1081. lõppfailid kokku paneb; default genereeribki javadoci outputist HTML failid;
  1082. - javadoc generates html file for each java class;
  1083. - Javadoc works by reading source files and generates
  1084. document based on a doclet. The standard doclet in
  1085. Javadoc generates HTML files.
  1086.  
  1087. + Application Deployment
  1088. - technology for Java application deployment is Java Web Start (JWS); it's a tool
  1089. that runs on the Java Network Launching Protocol (JNLP).
  1090. - in short, to deploy, you need to package it in a jar file and create a JNLP file
  1091. that describes the jar file; may also include instructions for user on what to do
  1092. to download and install the application;
  1093. - typically you tell JWS what to do using a JNLP file:
  1094. - if there's no JRE installed on comp, Java Web Start can download the latest ver
  1095. of JRE and install;
  1096. - if JRE is incorrect ver; downloaded JRE is only used to run this app and will
  1097. not affect the old JRE;
  1098. - if there is correct JRE, JWS will simply run the application;
  1099. - JWS is installed as part of the JDK;(või on see typo ning tegelt JRE?)
  1100. - JNLP file is a xml;
  1101. - failis on lisaks igast muid tage, mis sisaldavad infot faili enda codebase'i kohta
  1102. (url), min ver of JWS, desc of app etcetcetc;
  1103. - lol, tuleb välja et jnlp faili loetaksegi browseriga;
  1104.  
  1105.  
  1106.  
  1107.  
  1108.  
  1109.  
  1110.  
  1111. KÜSSID:
  1112. - Integer Bitwise Operators & | ^
  1113. - kui parentil on defieneritud 1 konstruktor, mis sööb 1 argumendi, siis
  1114. selle parenti pärinud child failib, kui explicitly ei kutsu seda konstrukotrit välja.
  1115. mis sellisel juhul automaatselt no-arg konstruktorit ei provide'ita?
  1116. - mis maagia käib swingi alguses @ main method? (swingUtilities.invokeLater...
  1117. seal mingi anonymous method?)
  1118. - mida tähendab super(); meetodis enne teist meetodit (mitte alati vist?);
  1119. - 24. pt jäi üsna segaseks (kuidas täpselt Callable ja Future kasutada nt;)
  1120. - vaata Serializable üle
  1121. - ehk serialization - wuts dat. üks artikkel sel teemal:
  1122. http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html
  1123. - SO-st üks seletus:
  1124. "In other words, serializable objects can be written to streams, and hence files, object databases, anything really."
  1125. - vaata reflection üle
  1126. - Java reflection allows you to analyze a Java class and use the information contained in this class at runtime.
  1127. - 13, punkt @ http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html
  1128. - miks on seal eraldi veel "public abstract String color() tarvis defineerida?; st miks ei piisa iga enumi color() override'ist?"
  1129.  
  1130.  
  1131. + KASULIKUD LINGID:
  1132. - spring web (get/post, data saatmine/kuvamine via .JSP, authorisation, login,
  1133. ... : http://bitbybitblog.com
  1134. - sama link viitab veel parema autentimiseni (LDAP serveriga) @ spring docs:
  1135. http://docs.spring.io/spring-security/site/docs/3.0.x/reference/ldap.html
  1136. - üks äge protokolli implementatsioon (see google proto):
  1137. https://developers.google.com/protocol-buffers/docs/javatutorial
  1138.  
  1139.  
  1140. + frameworks:
  1141. - conteinerid (nagu spring) hivemind, picocontainer (mõlemad VIST samuti peamiselt
  1142. dependency injectioniks)
  1143. - testing: mockito, easymock, jmock;
  1144. - boneCP - db connection pooling (btw, väidetavalt tomcatiga polegi endal vaja pooli tekitada: http://stackoverflow.com/questions/13792469/basic-db-connection-pool-with-java-and-tomcat-7
  1145. btw2: boneCP conn pooliga pole endal vaja sünkroniseerida, kuna on juba seesmiselt
  1146. lahendatud);
  1147. btw3: boneCP pole enam kiireim, selle SO vastuse kohaselt:
  1148.  
  1149.  
  1150. + randomit:
  1151. - Dependency Inversion Principle (DIP):
  1152. 1. HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
  1153. 2. ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS.
  1154. - thread safety kohta lugemis:
  1155. - http://www.javaworld.com/article/2072798/java-web-development/write-thread-safe-servlets.html
  1156. - http://www.javaranch.com/journal/200603/Journal200603.jsp#a5
  1157. - http://www.vipan.com/htdocs/usefulservlets.html
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement