Monday, February 29, 2016

[Java] hashCode() and equals()

The set use hashCode() and equals() to decide if the value exists already :

so when override equals() , you have to override hashCode() , too.

and should respect :
if equals() return true, hashCode must be the same,
if hashCode() different, equals must return false.

ex :
class People{
    private String name;
    private int age;
     
    public People(String name,int age) {
        this.name = name;
        this.age = age;
    }  
     
    public void setAge(int age){
        this.age = age;
    }
         
    @Override
    public boolean equals(Object obj) {
        return this.name.equals(((People)obj).name) && this.age== ((People)obj).age;
    }
}
 
 
public class Main {
 
    public static void main(String[] args) {
         
        People p1 = new People("Jack", 12);
        System.out.println(p1.hashCode());
             
        HashMap<People, Integer> hashMap = new HashMap<People, Integer>();
        hashMap.put(p1, 1);
         
        System.out.println(hashMap.get(new People("Jack", 12))); //---> null hashCode is not defined, the program will test the hashCode, and find hashCOde is different, so it think they are different object.(hashcode default projection is from address of the object to int)
    }
}
 
 
solution : override hashCode():

    public int hashCode() {
        return name.hashCode()*37+age;
    }
 attention :  to the changes of the members, the hashCode is nolonger the same, problem for get(key) : 
 
ex:
              People p1 = new People("Jack", 12);
        System.out.println(p1.hashCode());
             
        HashMap<People, Integer> hashMap = new HashMap<People, Integer>();
        hashMap.put(p1, 1);
        p1.setAge(12);
       
        System.out.println(hashMap.get(p1); ->>>>null

[Java] HashMap et HashTable

HashMap VS HashTable

Inherits:

public class Hashtable<K,V>  
                                             extends Dictionary<K,V>  
                                             implements Map<K,V>, Cloneablejava.io.Serializable
public class HashMap  extends AbstractMap implements Map

 Synchronization :

HashTable is synchronized,  can be used in multi-threading
HashMap is not, should manage synchronization in multi-threading

null key ? null value?:


HashTable do not allow null value or key
HashMap can have several null values and one null key

hash:

HashTable uses directly  the hashCode of an object : 
public synchronized V put(K key, V value) {  
...
        int hash = hash(key); 

....
}

private int hash(Object k) {  
        return hashSeed ^ k.hashCode();  
    } 


HashMap recalcule the hash value.
First use hash to check if same, if hash same, use "equals()" to check
hash(key.hashCode()); 
 

Expansion : (扩容)

 HashTable 11 by default, old*2+1 expansion
HashMap 16 by default, n^2 expansion : 16, 32,64.....


both use linked list for collisions

Saturday, February 27, 2016

[C++] Why C++ 's constructor is so different?

When I first saw this :

class A{
public:
        A(int a):_a(a){};
private:
        int _a;
}

I was lost : WHAT? why not right like Java :

class A{

   private int a;
   public   A(int a){
      this.a = a;
   };

}

Now I have the answer from << Effective C++>>  :

the compiler of C++ will trait the constructor as two step :
                               it will read : A(int a) : _a() then the part in {}

 So : when we do  this : A(int a):_a(a){}; 
compiler will created an object of A, and give the value of _a as a;
But: when we do this : A(int a){ _a = a;}; 
compiler will first create the object of a and give _a a default value,  then in the {} _a will be give a value as a again!

So we saw, the first advantage is we reduce the Assignment in {} to be more efficient;
the second is that, when your member is a custom defined class,  we have no idea what value will be give to the member in the first step : 
ex:        A(B b){_b = b;} ==> when compiler create the object A(B b), what value could be given to _b? we don't know! So it's better to avoid this uncertain thing from happening.


Thursday, February 25, 2016

[Life] Almost the End of my student career

About 10 days left for this semester, and maybe the last 10 days' life as a student.
I don't want to be too sad, but it's a millstone. I have been living as a student since 18 years ago (woooo, I am a old man now....)

Primary :  life has been always a circle for the first 6 years: semester&vacation, weed days&weekend, classes&homework, review&exam....  

middle-hight school: yeap.....the same things....

hight-school : Bingo, never like in American films, yes, worse, I have classes on SATURDAY and SUNDAY MORNING!

crazy .... than the GAOKAO (bac).

Its was really different in university : more freedom but I've gotten lazier; I learn to manage my life but truth is that the life manged me..... But much better than high school. 

Now TB, the last days here, I feel so lucky that I could come here. New life style, new culture, new think, and new life goal.
See original image

Don't waste these beautiful days, Jianfei !  

   

[C++] function and const

A member function defined is const :
A function_name(...) const
   this function will not modify the class member(except ones that are marked mutable).

A parameter is const : 
A function_name(const int c)
 this function will not change the input parameter.


[C++] defult defined functions by compiler

When you defined a class with nothing in it, the compiler will defined which function(s) for you ? 

class A{ }

1 constructor with non parameter A();
2 copy constructor : A(const A & a);
3 destructor ~A();
4 copy assignment : A& operator = (const A & a);

How to avoid the compiler defining these functions ?

 Override them

And how to avoid to use them ? 

override them as private

And how to avoid to use them in the class?

declare them but do not to define them

Tuesday, February 23, 2016

[C++] struct union enum

struct

struct student 
{
    char name[6]; 
    int age; 
    char* GetName(void){return name;};
    int GetAge(void){return age;};
};
 struct VS class : default in struct is public, default class is private

union

Union -> share the memory for all the members : when you create an union, compiler will give a space of the max size of all the members. and when you use on member and give a number, the value will be covered.

union score 
{
    int i_sc; 
    float f_sc;
    int GetInt(void){return i_sc;};
    float GetFloat(void){return f_sc;};
};

union VS class : 
1 Non inherit in union
2 Non virtual method
3 Default public in union  
4 Non static, non reference -> (because union cannot share the memory)
5 the class with constructor,copy constructor,destructor,copy assignment operator(拷贝赋值运算符), virtual function cannot be a member of union : this class shared the memory.

enum

enum color {red,blak,white,blue,yellow};



[C++] friend

Encapsulation is a principle of OOP -> private member not accessible to outer class.

But, some times, we need to access in some situation.

friend reduce the time for type casting and safety check, but destroy the encapsulation.

1 friend class :  class A can access the private members of class B
2 friend method : method can access the private members of the class

Relation friend cannot be inherited
Relation friend is single directed A->B cannot have B->A
Relation friend is not transitif : A->B B->C  cannot have A-> C
Friend method is not a class member method, it's declared in the class, but for definition, we cannot write class::function_name for the method.


      class Point
 4   {
 5   public:
 6     Point(double xx, double yy) { x=xx; y=yy; }//默认构造函数
 7     void Getxy();//公有成员函数
 8     friend double Distance(Point &a, Point &b);//友元函数
 9   private:
10     double x, y;
11   };
12 
13   void Point::Getxy()
14   {
15        cout<<"("<
16   }
17 
18   double Distance(Point &a, Point &b)  //注意函数名前未加类声明符
19   {
20       double dx = a.x - b.x;
21       double dy = a.y - b.y;
22       return sqrt(dx*dx+dy*dy);
23   }
24 
25   void main()
26   {
27        Point p1(3.0, 4.0), p2(6.0, 8.0);
28        p1.Getxy();
29        p2.Getxy();
30        double d = Distance(p1, p2);
31        cout<<"Distance is"<
32   } 
 
 
For me, it's better to use setter and getter but not friend !

Saturday, February 20, 2016

[C++] Reference & V.S. pointer *

Reference is an alias of some variable., it doesn't take space in memory.
Pointer is the address of some variable.

Use reference wherever you can, pointers wherever you must.

When you Define:

int a=1;   int *p=&a;
int a=1;   int &b=a;

Pointer can be const but not reference

Pointer can have many levels : **p but not reference

Pointer's value can be NULL, but reference cannot be , a reference should be initialize when defined.

Pointer's value can be changed, but not reference

sizeof(reference) gives back the size of the object, but sizeof(pointer) gives the size of the pointer not the object.

Use reference as a parameter of method :
void method(A & ra)
void method(A * pa)
The same effects as passing a pointer :
1we can do the operations on the object by using  this reference/ pointer
2 will not make a copy of this object in memory
Differences :
1 in fact, when we use pointer as input parameter, we use exactly the value-passing, just we pass the address as the value:
void test(int *p)
{
  int a=1;
  p=&a;
  // ---> p points to the value of a(1) in memory
}

int main(void)
{
    int *p=NULL;
    test(p);
    // ---> p points NULL, because test take the value of p, just an address value-passing
    return 0;
}

but reference is different, we do not copy any thing. 
void test(int *&p)//input is the reference of the value's point (a reference to the value's address)
{
  int a=1;
  p=&a;
  // ---> p is a reference, so here we change the p so we change the p in the main to a new address with value 1    
}

int main(void)
{
    int *p=NULL;
    test(p);
    // ---> p points 1, because test take the reference of the pointer
    return 0;
}


[C++] explicit

Ex:
struct A
{
    A(int) { }      // converting constructor
    A(int, int) { } // converting constructor (C++11)
    operator int() const { return 0; }
};
 
struct B
{
    explicit B(int) { }
    explicit B(int, int) { }
    explicit operator int() const { return 0; }
};
 
int main()
{
    A a1 = 1;      // OK: copy-initialization selects A::A(int)
    A a2(2);       // OK: direct-initialization selects A::A(int)
    A a3 {4, 5};   // OK: direct-list-initialization selects A::A(int, int)
    A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
    int na1 = a1;  // OK: copy-initialization selects A::operator int()
    int na2 = static_cast<int>(a1); // OK: static_cast performs direct-initialization
    A a5 = (A)1;   // OK: explicit cast performs static_cast
 
//  B b1 = 1;      // error: copy-initialization does not consider B::B(int)
    B b2(2);       // OK: direct-initialization selects B::B(int)
    B b3 {4, 5};   // OK: direct-list-initialization selects B::B(int, int)
//  B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int)
//  int nb1 = b2;  // error: copy-initialization does not consider B::operator int()
    int nb2 = static_cast<int>(b2); // OK: static_cast performs direct-initialization
    B b5 = (B)1;   // OK: explicit cast performs static_cast
}
 
Specifies constructors and conversion operators  that don't allow implicit conversions or copy-initialization.


EX : 
class String{
      explicit String(int n);
      String(const char *p);
};
String s1 = 'a'; //error:不能做隐式char->String转换 implicit conversition
String s2(10);   //correct:调用explicit String(int n);
String s3 = String(10);//correct:调用explicit String(int n);再调用默认的复制构造函数 (Initialization by copy)
String s4 = "Brian"; //correct:隐式转换调用String(const char *p);再调用默认的复制构造函数
String s5("Fawlty"); //correct:正常调用String(const char *p); 
 
void f(String);
­
String g(){
    f(10); //error:不能做隐式int->String转换
    f("Arthur"); //correct:隐式转换,等价于f(String("Arthur"));
    return 10; //error:不能做隐式int->String转换 should be : return (B)10;
}


Tips :

In reality,  implicit conversions or copy-initialization would cause some problems if we don't pay attention. So it's better to forbidden these. We use explicit before constructor or operator, to tell the compiler not to do the copy-initialization or implicit conversation.

[C++] Abstract class

EX :
class AbstractClass {
public:
  virtual void AbstractMemberFunction() = 0; // Pure virtual function makes
                                             // this class Abstract class.
  virtual void NonAbstractMemberFunction1(); // Virtual function.

  void NonAbstractMemberFunction2();
};

Pure virtual function : must be overridden

Abstract class cannot be initialized (cannot to create  object), but we can use a abstract class as pointer 's type to realize polymorphism.   

Friday, February 19, 2016

[C++] Heap and stack in memory

A C++ compiler will use the fallowing parts :

1 stack:  methods' parameter name, local variable name, FIFO, Allocat/ free by compiler
2 heap:  new objects, alloc/free by programmer
3 static(global) : global variable and static variable
4 const string
5 function body

int global_1=1000;//静态变量 外部链接性 常量表达式 初始化
int global_2;//静态变量 外部链接性 零 初始化
static int one_file_1=1000;//静态变量 内部链接性 常量表达式 初始化
static int one_file_2;//静态变量 内部链接性 零 初始化
int main()
{
static int count_1=1000;//静态变量 无链接性 常量表达式 初始化
static int count_2;//静态变量 无链接性 零 初始化
return 0;
}


//main.cpp   
  int   a   =   0;   全局初始化区   
  char   *p1;   全局未初始化区   
  main()   
  {   
  int   b;   stack    compilation
  char   s[]   =   "abc";   stack compilation   
  char   *p2;   stack, compilation for the symble 
  char   *p3   =   "123456";   123456/0 on const string ,p3 is on stack, compilation   
  static   int   c   =0;   Static  compilation
  p1   =   (char   *)malloc(10);  heap    run time
  p2   =   (char   *)malloc(20);    heap run time
  分配得来得10和20字节的区域就在堆区。   
  strcpy(p1,   "123456");  
123456/0 on const string , compiler may optimize it to the same place as thep3's string in the const String.
  }    


using stack (A a(5)) is more easy cause the compiler will manage the malloc/free,
using heap (A* a=new A(5)) is more powerful but we should manage the malloc/free(new/delete).



http://www.cnblogs.com/hanyonglu/archive/2011/04/12/2014212.html

[Java] Heap and stack in memory

Heap and stack are managed by JVM, programmer cannot access the operations.

Stack is faster than Heap, but the data in stack should has a certain size and life time.
Data in Stack can be shared by several stacks and several threads.

Heap is more dynamic : size of data can be allocated dynamically, the compiler does not need to know the life-circle. Disadvantage is should be allocated in run time , read/write slower.

Stack : is for storing the local variables and method calling
Heap: is where the variable refers to (the object created)

See original image
ex :

public class Memory {
    public static void main(String[] args) { // Line 1
        int i=1; // Line 2
        Object obj = new Object(); // Line 3
        Memory mem = new Memory(); // Line 4
        mem.foo(obj); // Line 5
    } // Line 9
    private void foo(Object param) { // Line 6
        String str = param.toString(); //// Line 7
        System.out.println(str);
    } // Line 8
}
 
 


Stack -- > java.lang.stackOverFlowError
Heap --> java.lang.OutOfMemoryError

Tow types of data in Java :
Primitive type :  int, short,  long, byte,  float, double, boolean, char (no String!!)
This type of data is defined like : int a =5; long b = 255l; named  Automatic Variable . For example, the  Automatic Variable 3, we know it's size and we know its life circle(in the code block), so we store them in stack :
1 it's faster
2 it can be shard
ex :
int a= 3; int b=3; b=2;

int a=3; ---> compiler want a Automatic Variable 3, it cannot find in the stack, so , it created a 3;
int b=3; ----> compiler can reuse the 3 created last step.
 b= 2; ---> compiler create a 2 and refer the b to this 2. so the a is still 3.

 Class types : classes, like : Integer, Object...use new to create an object
 All these objects are stored in HEAP , object is created dynamically (create when you need)
String is special:
String s = "string";
the compiler will try to find if we have already "string"    in the run time constant pool:
ex :
String str1="abc";
String str2="abc";
System.out.println(str1==str2);//true
 
True for "==" means they have the same address (equals() is for testing values)
So String is immutable! when you change its value, JVM has created a new String in the String pool.

String str1="abc";
String str2=new String("abc");
System.out.println(str1==str2);//false!!! str2 is in heap, str1 is in string pool



[C++] Destructor

Constructor

have the same name as class, non return type
What a constructor does ? 
1 create a symbol for the object
2 reserve memory space for the object
3 initialize the members
ex :
class A{
public:
          A(){cout<< "Constructor"<<endl;};
          ~A(){cout<< "destruct"<<endl;}
}


int main(){
       A a; // ------> Constructor is
......
// ------> Destructor is called
}

Destructor

destructor cannot have parameters (cannot be overloaded)  : one class can have only one destructor.  If user not define, compiler will generate a destructor.


destructor is called when the object is destroyed. So when we destroy an object ? 
(scope and lifecycle)
1: in amethod : you defined a local object variable, when the method finished, this local object will be destroyed

2 : static local variable  and global variable will not be destroyed until the process is finished : the end of the main or when we call exit

 1 Base class' destructor and sub class' destructor


the order of calling destructor is :
subclass' destructor --> base class' destructor

the order of calling constructor is Converse : 
base class' constructor --> subclass' constructor

2 if the base class' destructor is not virtual :

the subclass' destructor will not be called, and the subclass' own members will not be released after destruction. 

ex : 
class Base{
private:
         int* number_  = new int(0) ;
public: 
          Base() {};
          ~Base(){ delete number_;};
}

class Sub:Base{
private:  
        float* speed_ = new float(0f);
public :
        Sub(int num, float speed):Base(num):speed_(speed){};
        ~Sub(){delete speed_;};
}

3 destructor will be called automatically in the end 

And the calling order is revered from creating order : a stack

int main(){
     A a(0);
     A b(1);
     A c(2);
     .....
     .....
///--> in the end, the destruct order is : c,b,a ---> stack !
}


but!!! when you use new,  it's different!!!

int main()
{
    A * a;
    a = new A();
    return 0;
///--> in the end, there is non destructor called !!
}

For C++, if you created the object with new,  then it's your responsibility to release the memory of this object: 

int main()
{
    A * a;
    a = new A();
    delete a;
    return 0;
}












 

4 destructor with int method :

class A
{
    public:
    A()
    {
        cout << "constructor" << endl;
    }
    ~A()
    {
        cout << "destructor" << endl;
    }
};
 
void function(A a)//--pass-by-value
{
 
}
 
int main()
{
    A a;
    function(a);
    return 0;
}
 
output : 
constructor
destructor
destructor!!
 
tow times of destructor:
function did a shallow copy, but the function will trait the object as an local object and call its destructor ---> illegal! we do not want to destroy the object so we  need to use :

pass-by-reference-to-const for parameter :

void function(const A& a)//--pass-by-reference-to-const
{
 
}

Thursday, February 18, 2016

[C++] new/delete, malloc/free, delete[]

1 new/delete  V.S. malloc/free

new will call the constructor and create object in memory (like malloc)
delete will call the destructor (~ClassName() ) and release the memory (like free)

free/malloc are the std library function in C/C++ otherwise new/delete are the operators of C++

why do we need new and delete in C++ :

in C++, when we need to create an object :
     1  reserve a space in the memory  2 execute the constructor
when we need to destroy an object :
     1  execute the destructor    2 release the memory of this object
malloc and free are std library functions and they are not in the control of compiler, so we cannot let them to call the constructor and destructo, thus we need new and delete to do this.


2 delete V.S. delete[]

delete will call the destructor once, but delete[] will call the destructor of every member :
when delete works on an array[], it will call the destructor of every member and than release the memory.
All you should remember is : use new with delete, use new[] with delete[]
ex :
MemTest *mTest1=new MemTest[10];
MemTest *mTest2=new MemTest;
Int *pInt1=new int [10];
Int *pInt2=new int;
delete[]pInt1; //-1-
delete[]pInt2; //-2-
 --> in this case, pInt2 can be a single int or can be an array with only one int, so delete and delete[] both work : for simple type pointer, delete and delete[] are the same, but for user defined complex type pointer , delete and delete[] are different.
delete[]mTest1;//-3-
delete[]mTest2;//-4- --> error : mTest2 is not an array, it's just a pointer

Thursday, February 11, 2016

[C++ vs Java] Differences

https://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B

the syntax is similar :

1 Objective : 

C++ is created based on C for  systems and applications programming.  

Java is created for Network Computing, objective is  portability  (once developed, execute everywhere, as few implementation dependencies as possible) Depends on a JVM to execute.


2 Memory management

C ++ : if we do not use smart pointer, it's the programmer's responsibility to manage the memory : allocation(new) and dislocation(delete) memory.

Java: it's the JVM (Garbage Collection) dose the management for us : jvm will count the reference of the objects, and when there is no more reference, the memory is released.

3 Object-oriented 

 C++ is procedure-oriented and object-oriented. But C++ is compatible with C, so it's possible to see C-like codes in C++. (Multi inheritance; class/struct ;  )

Java is object-oriented :  Abstract, Encapsulation, Inheritance, Polymorphism. (interface)

Bref : in a word, C++ est plus difficult ( memory management, syntax like containers, iterators...) than Java, we pass more time in learning how to use the language but not in solving the problem.

Tuesday, February 9, 2016

[Data Mining] ROC Curve

Receiver operating characteristic

https://en.wikipedia.org/wiki/Receiver_operating_characteristic
ROC : is for evaluating the binary classification models. 
EX :  in the Nearest neighbor search algo, when we difine different distance for the neighbors : distance < 50 is my neighbor VS distance<100 is my neighbor, we need ROC to tell which choice is better. 

How to make a ROC curve? 
for example, I have defined some rules for the neighbor and we have the result of 20 observations : 

individuscoreclasse
11+
20.95+
30.9+
40.85-
50.8+
60.75-
70.7-
80.65+
90.6-
100.55-
110.5-
120.45+
130.4-
140.35-
150.3-
160.25-
170.2-
180.15-
190.1-
200.05-
we will calcule 20 points : 
1 : we predict individu<=1  is +, the others are - : 
reality
+-
predictions
+10
-514
total614
so we get TPR = TP/P = 1/6 = 0.166; FPR = FP/F = 0/14 = 0
 --> the first point(0.166,0)

2 : we predict individu<=2  is +, the others are - : 
reality
+-
predictions
+20
-414
total614
so we get TPR = TP/P = 2/6 = 0.333; FPR = FP/F = 0/14 = 0
 --> the second point(0.333,0)
......

15 : we predict individu<=2  is +, the others are - : 
reality
+-
predictions
+69
-05
total614
so we get TPR = TP/P = 1; FPR = FP/F = 9/14 = 0.643
 --> the fifth point(1,0.643)
......

so we can have a curve like : 
the line x=y (0.5 ) means we cannot make decision with this prediction.
so , the surface bigger the better the model is. 
the surface names : AUC
if we have several model to compare : we should choose the one with biggest AUC.