Author: techfox9
Notes (Part 3) from HeadFirst Java..
Saturday, May 14th, 2005 @ 1:25 am
- — Basic network read pattern:
Socket socket = new Socket("someserver.com", 5000); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); BufferedReader reader = new BufferedReader(isr); String message = reader.readLine();
— Basic network write pattern:
Socket socket = new Socket("someserver.com", 5000); PrintWriter writer = new PrintWriter(socket.getOutputStream()); writer.println("message to send");
- — Basic thread pattern
public class RunnableJob implements Runnable { public void run() { ... } } RunnableJob rj = new RunnableJob(); Thread thread = new Thread(rj); thread.start();
- — Thread data access synchronization
— If we synchronize two static methods in a single
class, a thread will need the class lock to enter either
of the methods. - — Collections
— ArrayList
— TreeSet – elements sorted, no duplicates.
— HashMap – name/value pairs.
— LinkedList – better performance for insert and delete of elements.
(better for large data sets)
— HashSet – no duplicates, fast search by key.
— LinkedHashMap – same as HashMap plus preserves order of addition. - — Basic sorting pattern:
ArrayList
slist = new ArrayList (); slist.add("a string"); slist.add("..."); Collections.sort(slist); New classes to be used with ArrayList must implement
“Comparable” (self compare).See the use of a comparator (call it MyCompare) which
implements the compare(MyObject, MyObject)
method, like this:Collections.sort(theList, new MyCompare());
- — Collection types summary:
— List – sequence.
— Set – uniqueness.
— Map – key search. - — HashSet duplicate check methods:
hashCode(), equals(). - — Control on polymorphic ‘collection type’ usage..
public void takeAnimals(ArrayList<? extends Animal> animals) { ... animals.add(someAnimal); // <-- add is forbidden by the '?' wildcard }
- -- Static nested classes have access to static variables
of the enclosing class.-- Anonymous nested classes have peculiar syntax capabilities:
button.addActionListener(new ActionListener() { public void actionPerformed() { System.exit(0); } } );
ActionListener is not a class, is an interface but in
this context the 'new' instruction means 'create an
anonymous class and implement the ActionListener
interface'. - -- Access levels and modifiers:
-- public - access by anybody.
-- protected - same package + subclasses in or out of
the same package.
-- default - same package only.
-- private - same class only. - -- Enumerations - a set of constant values that
represent the only valid values for a variable.public enum Members { JERRY, BOBBY, PHIL }; public Members bandMember; ... if (bandMember == Members.JERRY) { ... }