Sunday, January 31, 2016

[Java] Default of Arrays.asList and List.subList

Arrays.asList() :

int [] ints = {1,2,3,4}
List list = Arrays.asList(ints);
list.size() ->>>> 1 not 4

because :
public static <T> asList(T...a){
           return new ArrayList<T>(a); }

the input is generic type values T, but as ints is an int[], int is basic type , cannot be generilized.

so we can :
Integer [] ints = {1,2,3,4}
List list = Arrays.asList(ints);
list.size() ->>>>  4
but cannot list.add(1) // ->>> the ArrayList<T> here is not the java.util.ArrayList, it's an inner class of java.util.Arrays

List.subList() :

List<int> list1 = new ArrayList<int>(); list1.add(1); list1.add(2);

List<int> list2 = new ArrayList<int>(list1);

List<int> list3 = list1.subList(0, list.size());
list3.add(3);
...
list1.equals(list2) >>>>false  // not the same address
list1.equals(list3) >>>>true // same address ---> subList return a SubList, it's a inner class of ArrayList, all the operations are applied on the original list. i's just a mirror of original list.
after using  subList(), we should avoid doing operations on the original list : the modCount is copied to subCList too, so when we do the operation on the original list, there will be fail fast.

So, what sublist is for ?
it's for doing operation on some indexes of the list :

list1.subList(100,200).clear();        =        for(int i = 0;...){ if(i>=100&&i<=200) {list1.remove(i);}}

[Java]Fail-Fast

Fail-fast : failure condition is detected before damage can be done

ArrayList has a modCount :  any operation of modification can raise modCount (add, remove,clear.....).
When the Thread found the modCount != expectedModCount ----> a fail-fast

How to avoid : use thread safe containers (CopyOnWriterArrayList -> all add, remove operations are realized by copy the array). 

[Java] Collections



See original image

 Set : non duplication, non order
 List : can duplication, have order
 Map : <key, value> structure


Vector : 
array based (can be replaced by ArrayList)
re-sizable : 2 times re-size,
synchronous

ArrayList : 
array based,
re-sizable:1.5 time re-size, initial  default 10 ,
non-synchronous( solution : Collection.synchronizedList(new ArrayList) )
fast in looking up
slow in inserting and deleting

LinkedList:
linked node based,
fast in inserting and deleting
slow in looking up

HashMap:
non-synchronous
initial size = 16
use linkedlist to resolve collision
can have one null key and several null value

HashSet
non duplication HashMap(based on HashMap)

HashTable
synchronous
cannot have null key or null value

hashCode for domain searching
x.equals(y) == true ---> same Hashcode
x.equals(y) == false ---> hashcode can be same or different

Queue :
add() : add an element or Exception if it's full
remove() : remove and return the first element or Exception

offer() : add an element or return -1 if it's full
poll(): remove and return the first element or return null

put() : add an element or block if it's full


BlockingQueue -> blocking algorithm to realize the thread safty
ConcurrentLinkedQueue -> non-blocking algorithm for thread safty


[Java] Deep copy VS Shallow Copy

DeepCpoy - > copy instance
Shallow Copy -> copy reference

Interface Cloneable.clone() :
for basic type : int float --> deep copy
for Object type ->shallow copy

String is immutable !

[Java] Abstract and Interface

Abstract "is A"  abstraction of class

Can have member and non-abstract methods

Interface "like A" abstraction of behavior

ISP : Interface Segregation Principle : several specialized interfaces is better than mono interface with multiple behaviors.

[Java] RoundingMode 四舍五入

BigDecimal   i = (value) .setScale(2, RoundingMode.    MODE);

MODE :
ROUND_UP : away from 0         |<------------0------------->|
ROUND_DOWN : close to 0         |------------>0<-------------|

ROUND_CELLING :  to + infinity         |------------->|
ROUND_FLOOR :  to  - infinity            |<------------|


HALF_UP :   0.5 to 1  0.4 to 0       |<------------0.4 0.5------------->|
HALF_DOWN :   0.6 to 1  0.5 to 0       |<------------0.5 0.6------------->|

HALF_EVEN :  depends the value 5
                           ex : 11.4 ->11; 11.51->12;  
                                  11.503->12 (1 is impaired number)  ; 12.503-> 12 (2 is paired)
                                  11.6 -> 12




[Java] Leaning notes : Encpsulation, inhrit and polimophic




 From today, I started to collect my learning notes about Java.
Encapsulation, inherit and polymorphic

the three most important characteristics in Java

  Encapsulation

for : 
  1. dis-couple : reduce the dependency between the classes   
  2. easy to change the intern structure but not block the user of the class
  3. control of the access of the members  
  4. hind some informations

the principle usage of encapsulation is  the getter and setter   

 Inherit

 WHY : reuse the code! Inherit defines the relation (couple) between the classes. 
HOW :  
  1. the sub class has the parent's non - private members and methods 
  2. the sub class extends its own members and methods
  3. the sub class can override parent's methods
 Private :  just the class itself
 Protected : can be accessible by the sub classes and by the class in the same package
 A<--B : B is A (dog is animal)
When the parent changes, the sub classes need change too. So this damages the encapsulation.
WHEN : if we need transform type from sub class to parent, we need to use Inherit.  

 Polymorphic

 WHAT : we have a reference of an object, and this reference can refer to A or B. So the method called when we do Ref.method is not fixed in compilation, it's decided in runtime. 

 HOW : 
1. Inherit + transform to supper class + override method
              A
             /  \
           B    C
A a = new A();
A b = new B();
B b1 = new B();
A c = new C();

public class A{
    public f1(){...}//1
    public f2(){...}//2


public class B{
    public f1(String s){.....}//3
    public f2(){.......} //4
}

public class Test{
    ......
  A b = new B();
  b.f1(); -------> A.f1() : f1() is different from f1(String) -----> this is overlaod
  b.f2(); -------> B.f2() : f2() is override by B -----> this is override
    ......
}

Reference is parent type but the object is sub class type (A b = new B()): 
1. b ca only access A 's methods.
2. if the methods are override by B, the sub classes' methods will be called.

Advantages : the same operation apply on different classes will have different results, so we can use the same logic to trait different classes, (animal 's sub classes bird and dog can have different behaviors for the same method "eat()")



2.Interface (Multi-inherit)

 Class A | + void show(D obj){"A - D"}
                | + void show(A obj){"A - A"}
|      
|        
|           
class B | + void show(B obj){"B - B"}
               | + void show(A obj){"B - A"}
               |  + void show(D obj){"A - D"}//this tow methods can be accessed by B!!
                | + void show(A obj){"A - A"}//


|       \
|          \
|             \ 
|               \
classC     classD 

test: 
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();


a1.show(b); A A
a1.show(c);A A
a1.show(d); A D

a2   ..... b B A // B 's instance but reference type A, so it can just call A' s methods, because input b is type A, so it will call the A.show(A), but we found this method is override in B, so we call B.show(A)
a2   ..... c B A// same
a2   ..... d A D

b   ..... b B B
b   ..... c B B// B's object and B's reference, so it can call all method in B and in A. So we try :  B.show(C), there isn't this method, so we transport C to his father B, and we found B has the method B.show(B)
b   ..... d   A D//