Java Design Patterns

c82-java-prog-logo

Advanced Class

Design Pattern
Singleton
Factory
Builder
Deps Injection
Scale is large enough (then need Design Pattern)
Project Requirement
Epic Fantasy Story
Role Play Game (RPG)
Turn-based Strategy fighting system
Treasure Collection
Players
Pick Roles
NPC Roles
Analysis
Ability promotion
inner class
Builder
build()
too many parameters / integers / optional parameters, no context for parameters
Google Protobuf / Google AutoValue
immutable / mutable
Map (World)
X * Y grid
Each world[x][y] is a block
Block could be free path or obstacle
Block can trigger events
Events can fight or collect treasure
Multiple players are walking in the world
Singleton
if (instance == null) {
  synchronized(this) {
    if (instance == null) {
      instance = new World();
    }
  }
}
World (Block as shop, path, fight, obstacle)
Factory
Hide initialization from clients (low coupling)
Make a hub for registering and create new instances (high cohesion)
Dependency Injection
Service maintains the initialization dependencies
Client doesn’t need to know about that
Normally, service is provided by framework
Google Guide, Spring, AngularJS
Interactions
Controller
Gather models manipulations (controller -> world, player, battlefield)
Simplify models
Users interface will be simpler
Low coupling
Summary
Builder
– ProtoBuf
– AutoValue
Singleton
– Thread safe
Factory
– High Cohesion, low coupling
Deps Injection
Controller
Donate $5 to me for a coffee with PayPal and read more professional and interesting technical blog articles about web and mobile development. Feel free to visit my web app, WhizWallet, to apply for credit, store or gift cards, DealsPlus to browse daily deals and store coupons to save money.
Follow me @Yaoli0615 at Twitter to get latest tech updates.
Resources:

Core Java Volume I–Fundamentals (10th Edition) (Core Series)

Core Java, Volume II–Advanced Features (10th Edition) (Core Series)

Test-Driven Java Development

Java Concurrency in Practice

Java: An Introduction to Problem Solving and Programming (7th Edition)

Java 9 for Programmers (Deitel Developer Series)

Java SE8 for the Really Impatient: A Short Course on the Basics (Java Series)

Core Java for the Impatient

Java: The Beginners Guide for every non-programmer which will attend you trough your learning process

Java Deep Learning Essentials

Machine Learning in Java

Learning Reactive Programming With Java 8

Java 9 Programming By Example

Thinking in Java (4th Edition)

The Java EE Architect’s Handbook, Second Edition: How to be a successful application architect for Java EE applications

Java Artificial Intelligence: Made Easy, w/ Java Programming

Posted in CS Research&Application, Uncategorized | Tagged , | Leave a comment

Java Basic Object Oriented Concepts

c82-java-prog-logo

Lambda: {arguments} -> {statements}

Functional Interface: Comparator, Function, Predicates
Method Reference: Class::method
Default Method: implementation in Interface
Stream: map, reduce, sort, filter
Collectors: joining, toList, summingInt…
Map: putIfAbsent, computeIfPresent, Tree Node (separate chain)
Optional
Basic OO in Java
(Class is for code reuse, constructor saves time to initialize)
Data First
Class
A collection of variables and functions
To present  a concept
Abstraction
share some code or has connection (related)
Polymorphism
IS-A
Warrior/Mage/Doctor is a player
Override (same signature, same return value, different method) — Annotation
Abstraction represents different sub-types. (IS-A)
Subclasses have own behaviors.
Runtime Decide.
Player player = new Warrior / Mage / Doctor ();
player.hello(); // ok
player.attack(); // compile error, no attach method in Player class
Encapsulation (security, thread-safe, readability)
High Cohesion, Low Coupling — as inaccessible as possible
Private: this Class
package-private (default): Classes in same package
Protected: Subclasses + Classes in same package
Public: All
Interface
Interface vs Abstract Class
Interface (Description) — *able
Unrelated classes implement the interface (e.g. Comparable for human, animal, car)
Define a new data type (e.g. List)
Multiple inheritance types (e.g. List, Deque <= LinkedList)
Abstract Class (Code sharing basics)
Share code among classes
Share common non-public methods, variables
Share code which could change the state of object
If doesn’t share code, use Interface instead of Abstract Class, otherwise use Abstract Class.
Reflection
from instance to Object, it happens on runtime (i.e. use patch to add some new characters in a game without recompilation)
if (obj instanceof Object) {
  …
}
class (Class clz = p.getClass())
method
variable
Everything is class in Java
Generics
Class level generics
Method Generics
Bounded Types
Wildcards
class Box<T> { T object }
class Box<T,K,V> { T object,K object2,V object3}
T: type, E: element, K: key, V: value
Raw Type vs Generics
Box b = new Box(); // raw type
b.set(“hello”);
Integer c = (Integer) b.get(); // no compile error but runtime error
Box<String> b = new Box<>();
b.set(“hello”);
Integer c = (Integer)b.get(); // compiler will complain, will be safer
Generic Method
type (T, K, V) before return value type
Bounded Types
<T extends Comparable<T>>
Wildcards (no declaration beforehand)
public static void process(List<? extends Foo> list) {
  // …
}
public static void process(List<? super Integer> list) {
  // …
}
Summary
Class: collection, template of instances
Inheritance: reuse, extensibility
Abstraction: share code, template of template
Polymorphism: IS-A, override, runtime decision
Encapsulation: high cohesion, low coupling
Interface: vs Abstract Class
Reflection: from instance to class
Generics: template of classes / methods
Donate $5 to me for a coffee with PayPal and read more professional and interesting technical blog articles about web and mobile development. Feel free to visit my web app, WhizWallet, to apply for credit, store or gift cards, DealsPlus to browse daily deals and store coupons to save money.
Follow me @Yaoli0615 at Twitter to get latest tech updates.
Resources:

Core Java Volume I–Fundamentals (10th Edition) (Core Series)

Core Java, Volume II–Advanced Features (10th Edition) (Core Series)

Test-Driven Java Development

Java Concurrency in Practice

Java: An Introduction to Problem Solving and Programming (7th Edition)

Java 9 for Programmers (Deitel Developer Series)

Java SE8 for the Really Impatient: A Short Course on the Basics (Java Series)

Core Java for the Impatient

Java: The Beginners Guide for every non-programmer which will attend you trough your learning process

Java Deep Learning Essentials

Machine Learning in Java

Learning Reactive Programming With Java 8

Java 9 Programming By Example

Thinking in Java (4th Edition)

The Java EE Architect’s Handbook, Second Edition: How to be a successful application architect for Java EE applications

Java Artificial Intelligence: Made Easy, w/ Java Programming

Posted in CS Research&Application, Uncategorized | Tagged , | Leave a comment

Java 8 features

c82-java-prog-logo
Pass by value in Java
Primitive Value, copy

Object, copy of reference

Out of memory (Heap, method, copy of reference)
Stack overflow (Stack, object, instance)
Java 8 features
Lambda expression (interface, extract one abstract method, mark as function interface)
Method Reference
className::methodName
Methods in Interface
Default method vs Static method
(New Feature: default methods implementation in interface)

Purpose: This capability is added for backward compatibility so that old interface can be used to leverage Lambda expression)
Stream
filter()
sorted()
map()
reduce (string)
count()
distinct()
forEach()
collect()
Collectors
joining, toList, summingInt
Map – word count
computerIfPresent()
putIfAbsent()
getOrDefault()
Optional
ofNullable()
orElse()
Performance
HashMap, link (separate chain, o(n))=> Tree (o(logn))
java.util.Time (from Joda time)
Donate $5 to me for a coffee with PayPal and read more professional and interesting technical blog articles about web and mobile development. Feel free to visit my web app, WhizWallet, to apply for credit, store or gift cards, DealsPlus to browse daily deals and store coupons to save money.
Follow me @Yaoli0615 at Twitter to get latest tech updates.
Resources:

Core Java Volume I–Fundamentals (10th Edition) (Core Series)

Core Java, Volume II–Advanced Features (10th Edition) (Core Series)

Test-Driven Java Development

Java Concurrency in Practice

Java: An Introduction to Problem Solving and Programming (7th Edition)

Java 9 for Programmers (Deitel Developer Series)

Java SE8 for the Really Impatient: A Short Course on the Basics (Java Series)

Core Java for the Impatient

Java: The Beginners Guide for every non-programmer which will attend you trough your learning process

Java Deep Learning Essentials

Machine Learning in Java

Learning Reactive Programming With Java 8

Java 9 Programming By Example

Thinking in Java (4th Edition)

The Java EE Architect’s Handbook, Second Edition: How to be a successful application architect for Java EE applications

Java Artificial Intelligence: Made Easy, w/ Java Programming

Posted in CS Research&Application, Uncategorized | Tagged | Leave a comment

Java Basics (Sorting, Classes)

c82-java-prog-logo

Sorting

if same time complexity, check
# of swaps
# of comparisons
o(n^2)
Insertion sort > Bubble sort > Selection sort
in place (maybe only o(1) space)
stable (same numbers’ relative position are same, 2,3,4,5(1),5(2))
o(nlogn)
Quick sort
o(1) extra space (in place)
not stable (random pivot, swap)
Merge sort
o(n) extra space (not in place)
Collections.sort(List<E> list) { list.sort() }
ArrayList, LinkedList, Arrays.sort()
Primitive Value Array: Tuned Quick sort (not stable, more efficient in memory)
Object Array: Merge sort (stable, i.e. Students might be sorted by age first, then height)
Insertion Sort when length < 7
-1 or less, 0 as equal, 1 or more as larger
Comparator
interface Comparator<T>
int compare(o1,o2)
Comparable
interface Comparable<T>
int compareTo(o1)
Iterator
hasNext();
next();
Iterable
List, Set, Map
Utility Classes and Methods
Collections.sort()
Arrays.sort()
Arrays
Arrays.asList()
Arrays.binarySearch()
Arrays.copyOf / copyOfRange
Arrays.deepEquals / deepHashcode / deepToString
Arrays.equals()
Arrays.fill()
Arrasy.toString()
String
String.toCharArray()
Character
Character.isUpperCase()
Character.isDigit()
Character.isAlphabetic()
Character.isSpace()
Character.toUpperCase()
Character.getNumericValue()
Static & Final
Static (class variable, function, class (nested) class)
Static class: static inner class, isolated from enclosing class instance
Static method: isolated from enclosing class instance
Static variable: called by static method
Static initializer: (run only once, even before constructor)
Final
Final class (cannot extend)
Final method (cannot override)
Final variable (cannot change the reference, compile error, but can change object member, can only be assigned be once)
Finally (a block, must execute after throw exception whether it’s caught or not)
Constant variable should be upper case
Final / Finally / Finalize (clean up processing before object is garbage collected)
Donate $5 to me for a coffee with PayPal and read more professional and interesting technical blog articles. Feel free to visit my web app, WhizWallet, to apply for credit, store or gift cards, DealsPlus to browse daily deals and store coupons to save money.
Follow me @Yaoli0615 at Twitter to get latest tech updates.
Resources:

Core Java Volume I–Fundamentals (10th Edition) (Core Series)

Core Java, Volume II–Advanced Features (10th Edition) (Core Series)

Test-Driven Java Development

Java Concurrency in Practice

Java: An Introduction to Problem Solving and Programming (7th Edition)

Java 9 for Programmers (Deitel Developer Series)

Java SE8 for the Really Impatient: A Short Course on the Basics (Java Series)

Core Java for the Impatient

Java: The Beginners Guide for every non-programmer which will attend you trough your learning process

Java Deep Learning Essentials

Machine Learning in Java

Learning Reactive Programming With Java 8

Java 9 Programming By Example

Thinking in Java (4th Edition)

The Java EE Architect’s Handbook, Second Edition: How to be a successful application architect for Java EE applications

Java Artificial Intelligence: Made Easy, w/ Java Programming

Posted in CS Research&Application, Uncategorized | Tagged , | Leave a comment

Programming Reflection (Jun 8, 2017)

wpid-Programming-Wallpaper-3

1.  BITT Principle

Brute Force (暴力解法,低效/费空间)
Improvement (优化解法,高效/省空间)
Time and space complexity (时间/空间复杂度)
Test (测试)

2. Array is sorted and may have better performance (3Sum o(n^2) solution)

数组排序过后可能有奇效

3. Test cases are designed on purpose to test the functionality, not randomly selected.

In the example of 3sum problem,

test cases could be:

0, 1, 2 elements for input array to test shorter array than the requirement

[1, 0, 1] for no matched triplets

[-1, -1, -1, 2, 2, 2, 2] for many duplicate triplets

测试用例是用来测试具体功能的,并非任意设计。

 

Donate $5 to me for a coffee with PayPal and read more professional and interesting technical blog articles. Feel free to visit my web app, WhizWallet, to apply for credit, store or gift cards, DealsPlus to browse daily deals and store coupons to save money.
Follow me @Yaoli0615 at Twitter to get latest tech updates.
Resources:

Ruminations on C++: A Decade of Programming Insight and Experience

Posted in CS Research&Application, Intern&Job, Uncategorized | Tagged , | Leave a comment

Java Data Structure Summary

c82-java-prog-logo

Data Structure in Java
ArrayList — Resizable Array Implementation
1.5x resize if necessary

GC vs ARC
runtime vs compile time
https://stackoverflow.com/questions/7874342/what-is-the-difference-between-objective-c-automatic-reference-counting-and-garb

Right shift vs Division
1. faster
2. pure integer
3. no intermediate solution overflow issue (safer, avoid stack overflow)

append operation: Amortized o(1)

seamless

Resizable Array
Random Access: o(1)

ArrayDeque — Resizable Circular Queue
2x resize if necessary (bit operation)

LinkedList
Double Linked List in Java
8 bytes to store last or next pointer
Dynamic data structure

ArrayDeque is better for implementing Stack/Queue, for consecutive space, almost o(1) for head/tail operation

Queue queue = new ArrayDeque();
Queue queue = new ArrayDeque(1000); // avoid too much resize

List queue = new ArrayList(1000);
Deque stack = new ArrayDeque(1000);

Stack (Vector) is thread safe data structure, slower for cases which doesn’t need multi-thread

Hashing
build index (map object to number/hash code, many to one, ideal status is one to one)
Default: memory address
Hashcode design 3 principles:
1. same code for repeating calling in same application
2. Equal => same hash code
3. same hash code !=> Equal, but good to have

HashTable
Search an element in an array time complexity:
unsorted array with o(n)
sorted array with o(logn)

search in almost o(1), insert in almost o(1)

Use hashcode and array length to get index of array

Mapping: hashCode => arrayIndex
arrayIndex = hashCode % length

Collision:
Linear Probing (clustering in head or tail)
Separate Chain (Linked List)

Rehashing (Load Factor = number of entries / length, if over threshold like 75% and resize)

HashMap
Default value:
size: 16
load factor: 0.75
hash % length => hash & (length – 1)

X mod 2^n (X & (2^n – 1))

Map of List is slower than List of List

HashSet (HashMap wrapper class with dummy value)

LinkedHashMap
Linked List + Hashmap
LinkedList maintains the order for insertion

LRU (Least Recently Used) Cache

LinkedHashMap – maintain visit instead of insert order, handle size

TreeMap
Red-black Tree (self balanced binary searched tree) implementation
Mid-order Iteration (calculate )
o(logn): put, containsKey, remove
sorted keys

TreeSet (TreeMap wrapper class with dummy value)

Heap
Complete Tree (Each level must have max number of nodes, bottom level could be an exception, filled from left to right on each level)
Largest/smallest in the root
Children are always smaller/larger than parent

Add/Remove (sink up/down)
Keep complete tree structure
Keep parent-children value order

Remove the root only allowed

Store as array actually (childrenIdx – 1)/2 = parentIdx, leftChildIdx = 2 * parentIdx + 1, rightChildIdx = leftChildIdx + 1

PriorityQueue in Java (offer as add)

Practice: Top K Numbers

ArrayList: 1.5x resize(most operation on one side)
ArrayDeque: 2x resize (most operation on two sides)
HashMap: 2x resize (reduce the number of rehashing)

Donate $5 to me for a coffee with PayPal and read more professional and interesting technical blog articles. Feel free to visit my web app, WhizWallet, to apply for credit, store or gift cards, DealsPlus to browse daily deals and store coupons to save money.
Follow me @Yaoli0615 at Twitter to get latest tech updates.
Resources:

Core Java Volume I–Fundamentals (10th Edition) (Core Series)

Core Java, Volume II–Advanced Features (10th Edition) (Core Series)

Test-Driven Java Development

Java Concurrency in Practice

Java: An Introduction to Problem Solving and Programming (7th Edition)

Java 9 for Programmers (Deitel Developer Series)

Java SE8 for the Really Impatient: A Short Course on the Basics (Java Series)

Core Java for the Impatient

Java: The Beginners Guide for every non-programmer which will attend you trough your learning process

Java Deep Learning Essentials

Machine Learning in Java

Learning Reactive Programming With Java 8

Java 9 Programming By Example

Thinking in Java (4th Edition)

The Java EE Architect’s Handbook, Second Edition: How to be a successful application architect for Java EE applications

Java Artificial Intelligence: Made Easy, w/ Java Programming

Posted in CS Research&Application, Uncategorized | Tagged , | Leave a comment

Programming Reflection (Jun 1, 2017)

wpid-Programming-Wallpaper-3

1. Programming, programming, programming

Keep brushing up algorithm and data structure problems

Summarize the approach and the process to figure out solution

多刷题

多总结(回顾解题思路)

2. Technical Knowledge: Breadth vs Depth

Concentrate on one in early stage, then learn about more

职业早期专精一门,之后拓展广度

3. Tech stack: Old (Mature) vs New (Unstable)

Catch up with one or two new technology

Still use C++  for server side development for billion level usage (unless Java, or Node.js)

早期跟踪一两门新技术

4. Understand is more important than memorize solution

不要背题

 

Donate $5 to me for a coffee with PayPal and read more professional and interesting technical blog articles. Feel free to visit my web app, WhizWallet, to apply for credit, store or gift cards, DealsPlus to browse daily deals and store coupons to save money.

Follow me @Yaoli0615 at Twitter to get latest tech updates.

Resources:

Clean Code: A Handbook of Agile Software Craftsmanship

Ruminations on C++: A Decade of Programming Insight and Experience

 

Posted in CS Research&Application, Intern&Job, Uncategorized | Tagged , | Leave a comment