Morgan Stanley(摩根斯坦利)笔试加电面试题大全

2019-04-13 15:16发布

1经历了两次网上测试和两次电面,发现网上测试和电面题目都是不变的,电面题目相当固定,具体试题如下: (当时精心准备了所有的电面试题,整理出了两个word文档,有很多图片辅助理解,现在将重要内容写到这里,图片就不贴上来了,有需要的可以回复) 电面分若干小题与一道设计大题,小题都是考一些小知识点,如面向对象编程基础,大题两次电面都是一个题目,会议室预定的数据库设计,每个表包含哪些属性等,比较基础 电面试题 1.Index Data structure,stores the valueof specific colum in table,pointer to the row in table,allow for fasterretreaval of data in database,speed up search query. Hash index,not orderd,compare for equalitybut not for inequality. B-tree, allows logarithmic selections,insertions, and deletions in the worst case scenario. And unlike hash indexesit stores the data in an ordered way, allowing for faster row retrieval whenthe selection conditions include things like inequalities or prefixes. 2.stack vs heap Stack:static;compile time;LIFO order;memorymanagement automatically;access fast; Know how much data before compile,not toomuch; Heap:dynamic;run time;slower;size Islimited on virtual memory;allocat and free at any time; 3.thread vs process Thread:run in shared memory space;easier tocreate and terminate;lightweight;faster task-switching;data sharing with otherthread;care synchronization overhead of shared data; Process:separate memory space;independentof each other;consist of mutipule thread 4.Garbage Collection (GC) Mark:reffrence counting and reachability analysis; Clean up:sweep(hace fragment,old),coping(no fragment,eden),compact(nofragment,difficult to concurrent) Gennerational:(young:coping,old:mark-sweep/compact,permenant:class,const,staticvariable,method) CMS: Initial Mark, Concurrent Mark, Remark, Concurrent Sweep 5. Interface Vs Abstract method Abstract method:constants,members,methodstubs,defined method;any visibility;single class;chile class, with the same orless restrictive visibility Interface:const,methodstubs;public;multipul interface;child interface,same visibility; 6.sql join INNER JOIN: Returns all rows when there isat least one match in BOTH tables LEFT JOIN: Return all rows from the lefttable, and the matched rows from the right table RIGHT JOIN: Return all rows from the righttable, and the matched rows from the left table FULL JOIN: Return all rows when there is amatch in ONE of the tables 7. virtual method and inheritance Inheritance allows us to define a class in terms of another class, which makesit easier to create and maintain an application. This also provides anopportunity to reuse the code functionality and fast implementation time. 8. Primary key and foreign key PK:duplicated values not allowed;notnull;only one in a table; FK:duplicated;null;one or more in a table; 9. copy constructor and assignment operator copy constructor :Initialize a previous un-initialized object with the data of otherexist object; assignment operator: replace the data of a previously initialized object with some otherobject's data     10.pointer and reference Pointer:1.can bere-assign many times;2.can point to null;3.has its own memory address and sizeon stack;4.can have pointer to pointers to pointers offering extra levels ofindirection Reference;1.can’t bere-seated after binding;2.always refer to an object;3.share the same memoryspace with origin object;4.only one level indirection 11.polymorphsim Polymorphism is when you can treat anobject as a generic version of something, but when you access it, the codedetermines which exact type it is and calls the associated code  polymorphism is the ability (in programming)to present the same interface for differing underlying forms (data types). 12. what is staticmethod?  A static method is amethod that can be called on a class and usually does not require the class tobe instantiated. 13.what's thedifference between TCP and UDP? Reliability: TCP is connection-orientedprotocol.    Reliability: UDP is connectionlessprotocol. Ordered: don’t have to worry about dataarriving in the wrong order.  Ordered: If you send two messages out, youdon’t know what order they’ll arrive in i.e. no ordered Heavyweight: Lightweight: No ordering of messages, notracking connections, Streaming: Data is read as a “stream,” withnothing distinguishing where one packet ends and Datagrams: Packets are sentindividually and are guaranteed to be whole if they arrive. One packet 14. Smart pointer A smart pointer is a class that wraps a'raw' (or 'bare') C++ pointer, to manage the lifetime of the object beingpointed to Reference counted pointers are very usefulwhen the lifetime of your object is much more complicated, and is not tieddirectly to a particular section of code or to another object. 15.Exception and Error Errors tend to signal the end of yourapplication as you know it. It typically cannot be recovered from and shouldcause your VM to exit. Catching them should not be done except to possibly logor display and appropriate message before exiting. Example: OutOfMemoryError - Not much you can do as your program can no longer run. Exceptions are often recoverable and evenwhen not, they generally just mean an attempted operation failed, but yourprogram can still carry on. Example: IllegalArgumentException - Passed invalid data to a method so that method call failed, but itdoes not affect future operations. 16. Sleep() VS wait() Sleep:Thread类的静态方法,虽然休眠,但是锁并未释放,是当前线程进入停滞状态,让出cpu Wait:object类的方法,进入等待池中,释放对象的锁;使用notify或notify all 唤醒等待池中的线程。Wait必须放在synchronize Blocking中,否则runtime 抛出illegalMonitorStateException。     17.C++ vs C 1C is a structural or proceduralprogramming language. C++ is an object oriented programminglanguage. 2Functions are the fundamental buildingblocks. Objects are the fundamental buildingblocks. 3In C, the data is not secured. Data is hidden and can’t be accessed byexternal functions. 4C uses scanf() and printf() function forstandard input and output. C++ uses cin>> and cout<< forstandard input and output. 5. C doesn’t support exception handlingdirectly. Can be done by using some other functions. C++ supports exception handling. Done byusing try and catch block. 6. Features like function overloading andoperator overloading is not present. C++ supports function overloading andoperator overloading. 18. diffrence between Java and C++ Garbage collection/delete 1.Everything must be in a class. There areno global functions or global data. If you want the equivalent of globals, makestatic methods andstatic data within a class. There are no structs orenumerations or unions, only classes. 2.Write once, run anywhere, but it's stillmuch easier than writing a C++ cross-platform code. 3.C++ supports multiple class inheritance,while Java only gives you a single class inheritance, but solves themultiplicity via interfaces. 4.C++ has got a pointers, and can directlymanipulate/violate the memory addresses. 5.At compilation time Java Source codeconverts into byte code .The interpreter execute this byte code at run time andgives output .Java is interpreted for the most part and hence platformindependent. C++ run and compile using compiler which converts source code intomachine level languages so c++ is plate from dependents Java uses compiler and interpreter both andin c++ their is only compiler C++ supports operator overloading multipleinheritance but java does not. C++ is more nearer to hardware then Java Everything (except fundamental types) is anobject in Java (Single root hierarchy as everything gets derived fromjava.lang.Object). Java does is a similar to C++ but not haveall the complicated aspects of C++ (ex: Pointers, templates, unions, operatoroverloading, structures etc..) Java does not support conditional compile(#ifdef/#ifndef type). Thread support is built-in Java but not inC++. C++11, the most recent iteration of the C++ programming language does haveThread support though. Internet support is built-in Java but notin C++. However c++ has support for socket programming which can be used. Java does not support header file, includelibrary files just like C++ .Java use import to include different Classes andmethods. Java does not support default argumentslike C++. There is no scope resolution operator :: inJava. It has . using which we can qualify classes with the namespace they camefrom. There is no goto statement in Java. Exception and Auto Garbage Collectorhandling in Java is different because there are no destructors into Java. Java has method overloading, but nooperator overloading just like c++. The String class does use the + and +=operators to concatenate strings and String expressions use automatic typeconversion, Java is pass-by-value. Java does not support unsigned integer 19.privateconstructor: 1.    The constructor can only be accessedfrom static factory method inside the class itself.Singleton can also belong to this category. 2.    A utility class, that only contains static methods. Protected constructor When a class is (intended as) an abstractclass, a protected constructor is exactly right. In that situation you don'twant objects to be instantiated from the class but only use it to inherit from. There are other uses cases, like when acertain set of construction parameters should be limited to derived classes. 20sql注入injection submit a database SQL command that is executed by a webapplication,exposing the back-end database. A SQL injection attack can occurwhen a web applicationutilizes user-supplied data without proper validation orencoding as part of a command or query ·        when data entered by users issent to the SQL interpreter as a part of a SQL query. ·        Attackers provide speciallycrafted input data to the SQL interpreter and trick the interpreter to executeunintended commands. ·        A SQL injection attack exploitssecurity vulnerabilities at the database layer. By exploiting the SQL injectionflaw, attackers can create, read, modify or delete sensitive data.

Preventing SQL Injection

·        Youcan prevent SQL injection if you adopt aninput validation technique in which user input isauthenticated against a set of defined rules for length, type and syntax and also against businessrules. Youshould ensure that userswith the permission to access the database have the least privileges. ·        Usestrongly typed parameterized query APIs with placeholder substitution markers, even when calling storedprocedures. 21.Multithread designpattern(多线程设计模式) Single Threaded Execution: 只允许单个线程执行对象的某个方法,以保护对象的多个状态。 实现时需用synchronized修饰引用受保护的状态的方法,这样就只能有单个线程访问该方法,其它线程由于不能获取锁而等待。但是用synchronized保护变量也带来了性能问题,因为获取锁需要时间,并且如果多个线程竞争锁的话,会让某些线程进入这个锁的条件队列,暂停执行,这样会降低性能。 Immutable: 如果状态根本不会发生变化,就不需要用锁保护,这就是Immutable模式。 Person类用final修饰,防止被继承。_name_address都用final修饰,防止被修改,只能在定义时初始化,或者在构造器里初始化,Person类也只提供了对这些状态字段的get方法, Guarded Suspension: 当我们调用对象某个的某个方法时,可能对象当前状态并不满足执行的条件,于是需要等待,这就是GuardedSuspension模式。只有当警戒条件满足时,才执行,否则等待,另外对象必须有改变其状态的方法。 Balking: Balking模式与Guarded Suspension模式相似,都是在对象状态不符合要求时需要进行一些处理,不过Guared Suspension在状态不满足要求时,会等待并阻塞线程,而Balking模式是直接返回,并不等待。调用者可暂时先做别的工作,稍后再来调用该对象的方法。 不想等待警戒条件成立时,适合使用Balking模式。 警戒条件只有第一次成立时,适合使用Balking模式。 Producer-Consumer: 在该模式里可能有多个生产者,多个消费者,生产者和消费者都有独立的线程。其中最关键的是放置数据的缓冲区,生产者和消费者在操作缓冲区时都必须同步,生产者往缓冲区放置数据时,如果发现缓冲区已满则等待,消费者从缓冲区取数据时如果发现缓冲区没有数据,也必须等待。当程序里有多个生产者角 {MOD}或者多个消费者角 {MOD}操作同一个共享数据时,适合用生产者消费者模式。比如下载模块,通常会有多个下载任务线程(消费者角 {MOD}),用户点击下载按钮时产生下载任务(生产者角 {MOD}),它们会共享任务队列。 Read-WriteLock: 先前的几个多线程设计模式里,操作共享数据时,不管如何操作数据一律采取互斥的策略(除了Immutable模式),即只允许一个线程执行同步方法,其它线程在共享数据的条件队列里等待,只有执行同步方法的线程执行完同步方法后被阻塞的线程才可在获得同步锁后继续执行。 这样效率其实有点低,因为读操作和读操作之间并不需要互斥,两个读线程可以同时操作共享数据,读线程和写线程同时操作共享数据会有冲突,两个写线程同时操作数据也会有冲突。 Deadlock Mutualexclusion - Each resource is either currentlyallocated to exactly one process or it is available. (Two processes cannotsimultaneously control the same resource or be in their critical section). Holdand Wait - processes currently holding resourcescan request new resources. Nopreemption - Once a process holds a resource, itcannot be taken away by another process or the kernel. Circularwait - Each process is waiting to obtain a resourcewhich is held by another process. 22.Desing pattern FactoryMethod: The Factory Method Pattern defines aninterface for creating an object, but lets subclasses decide which class toinstantiate. Factory Method lets a class defer instantiation to subclasses.  

0. Programming

Index

Indexing is a way of sorting anumber of records on multiple fields. Creating an index on a field in a tablecreates another data structure which holds the field value, and pointer to therecord it relates to. This index structure is then sorted, allowing BinarySearches to be performed on it. The downside to indexingis that these indexes require additional space on the disk,since the indexes are stored together in a table using the MyISAM engine, thisfile can quickly reach the size limits of the underlying file system if manyfields within the same table are indexed. , the cardinality or uniqueness of the data isimportant.  With such a low cardinality the effectivenessis reduced to a linear sort, and the query optimizer will avoid using the indexif the cardinality is less than 30% of the record number, effectively makingthe index a waste of space.

1.  Stack VS Heap 

Stack : Static memory allocation Don’t need to Manage the memory by ourselves, variable canbe allocated automaticlly Access fast Space is effient used,not fragment Heap: Dynamic memory allocation Must manage the memory,in charge of allocating and freeingthe variables,or it maybe lead to memory leak. Access slow Space is not edffient    

GarbageCollection

http://www.cnblogs.com/zhguang/p/3257367.html http://blog.csdn.net/u014536596/article/details/49824659 Mark 引用计数算法(ReferenceCounting 可达性分析算法(ReachabilityAnalysis
  • 可以作为GC Roots的对象包括以下几类:
    • 虚拟机栈中引用的对象
    • 方法区中类静态属性引用的对象
    • 方法区中常量引用的对象
    • Native方法引用的对象

Clean Up

清理阶段。将Mark阶段标记出的不可用对象清除,释放其所占用的内存空间。主要有以下几种实现方式。

·        清除(Sweep

算法思想:遍历堆空间,将Mark阶段标记不可用的对象清除。
不足:效率不高;空间问题,多次清除之后会产生大量的内存碎片。
适用场景:对象寿命长的内存区域。

·        复制(Copying

算法思想:将内存划分为两个区域(大小比例可调整),每次只用其中一块,当此块内存用完时,就将存活对象复制到另一块内存中,并对当前块进行内存回收。
优点:解决了内存碎片问题;内存分配效率提高。每次复制后对象在堆中都是线性排列的,因此内存分配时只需移动堆顶指针即可。
不足:如果对象的存活率较高,大量的复制操作会显著的降低效率;内存空间浪费,每次都只能使用堆空间的一部分,代价高昂。

·        整理(Compacting

算法思想:将标记的所有可用对象向内存一端移动,然后直接清理边界以外的内存区域即可。
优点:类似于复制算法,解决了内存碎片问题,内存分配效率提高;消除了复制算法对内存空间的浪费。
不足:难以做到并行。

分代回收(Generational

前面所述的Mark-Clean算法都是针对整个堆区域的,每一次GC运行都需要对堆中所有的对象进行遍历。因此,随着堆中对象数量的增多,GC的效率就会随之下降。于是,GC对程序运行做出如下假设:
  • 大多数对象都会在创建后不久死亡
  • 如果对象已存活一段时间,那它很可能会继续存活一段时间
    GC过程 1. new objects allocated eden space. Both survivor spaces startout empty. 2. When the eden space fills up, a minor garbage collection istriggered. 3. Referencedobjects are moved to the first survivor space. Unreferenced objects are deletedwhen the eden space is cleared. 4. At the next minor GC, the same thing happens for the edenspace. Unreferenced objects are deleted and referenced objects are moved to asurvivor space. However, in this case, they are moved to the second survivorspace (S1). In addition, objects from the last minor GC on the first survivorspace (S0) have their age incremented and get moved to S1. Once all survivingobjects have been moved to S1, both S0 and eden are cleared. Notice we now havedifferently aged object in the survivor space. 5. At the next minor GC, the same process repeats. However thistime the survivor spaces switch. Referenced objects are moved to S0. Survivingobjects are aged. Eden and S1 are cleared. 6. This slide demonstrates promotion. After a minor GC, when agedobjects reach a certain age threshold (15 in this example) they are promotedfrom young generation to old generation. 7. As minorGCs continue to occure objects will continue to be promoted to the oldgeneration space. 8. So that pretty much covers the entire process with the younggeneration. Eventually, a major GC will be performed on the old generationwhich cleans up and compacts that space. 两个最基本的java回收算法:复制算法和标记清理算法 复制算法:两个区域A和B,初始对象在A,继续存活的对象被转移到B。此为新生代最常用的算法 标记清理:一块区域,标记要回收的对象,然后回收,一定会出现碎片,那么引出 标记-整理算法:多了碎片整理,整理出更大的内存放更大的对象 两个概念:新生代和年老代 新生代:初始对象,生命周期短的 永久代:长时间存在的对象 整个java的垃圾回收是新生代和年老代的协作,这种叫做分代回收。 P.S:Serial New收集器是针对新生代的收集器,采用的是复制算法         Parallel New(并行)收集器,新生代采用复制算法,老年代采用标记整理         Parallel  Scavenge(并行)收集器,针对新生代,采用复制收集算法        Serial Old(串行)收集器,新生代采用复制,老年代采用标记清理         Parallel   Old(并行)收集器,针对老年代,标记整理        CMS收集器,基于标记清理        G1收集器:整体上是基于标记清理,局部采用复制   综上:新生代基本采用复制算法,老年代采用标记整理算法。cms采用标记清理。   优缺点: The intention of GC is to reduce the difficulty in memory management and avoid sometypical memory related errors, i.e. ssegment fault, memory leak. you can callGC.collect() to notify the GC to work, but there's no guarantee that the memorywill be recycled immediately. It alldepends on the complicated algorithm of GC, butunfortunately it is non-deterministic. So, in anapplication which needs to manage memory very efficiently such as aserver using Gigabytes of memory,it should be able to allocate and releasememory in a deterministic manner,in this case GChurts. The common OOM issue in languages with GC is partly because unreferencedobjects pending for being collected still take a lot of memory, finally thesystem runs into OOM at a point. When OOM happens, it's even harder to resolvethan resolving memory issues in languages like C/C++. GC also bringsnon-deterministic in latency.In real-time systemssuch as a stock trading system, latency is usually considered much moreimportant than throughput. The system should keep latency as lowas possible, butthe timing of GC is non-deterministic, it's notcontrolled by programmers too. When GC is executing, the latency canbe several orders of magnitude higher than that when it's idle. This kind ofbehavioris not acceptable in real-time systems because it needs to respond torequests with low and deterministic latency. GC tuning into two.
  1. One is to minimize the number of objects passed to the old area;
  2. and the other is to decrease Full GC execution time.
 

3.Interface Vs Abstract method

The key technical differences betweenan abstractclass and an interface are: ·        Abstract classes can have constants, members, method stubs (methodswithout a body) and defined methods, whereas interfaces can only have constants and methods stubs. ·        Methods and members of an abstract classcan be defined with any visibility, whereas all methods of an interface must be definedas public (they are defined public by default). ·        When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an anabstract class can extend another abstract class and abstract methods from theparent class don't have to be defined. ·        Similarly, an interface extending another interfaceis not responsible for implementing methodsfrom the parentinterface. This is because interfaces cannot define any implementation. ·        A child class can only extend a single class (abstractor concrete), whereas an interface can extend or a class can implement multiple other interfaces. ·        A child class can define abstract methodswith the same or less restrictive visibility,whereas a class implementing an interface must define the methods with theexact same visibility (public).  

3.   SQL JOIN

INNER JOIN: Returns all rows when there isat least one match in BOTH tables LEFT JOIN: Return all rows from the lefttable, and the matched rows from the right table RIGHT JOIN: Return all rows from the righttable, and the matched rows from the left table FULL JOIN: Return all rows when there is amatch in ONE of the tables  

4.   virtual method and inheritance

Inheritanceallows us to define a class in terms of another class, which makes it easier tocreate and maintain an application. This also provides an opportunity to reusethe code functionality and fast implementation time. 5.      Primary key and foreign key

copy constructor and assignment operator

Acopy constructor is used to initialize a previously uninitialized object fromsome other object's data. Anassignment operator is used to replace the data of a previously initialized objectwith some other object's data.

7.Thread vs Process

Both processes and threads are independentsequences of execution. The main difference is thatthreads(of the same process) run in a shared memory space, while processes run inseparate memory spaces. 1.Threads are easierto create than processes since they don't require a separate addressspace.                              2.Multithreading requires careful programming since threads share data strucuresthat should only be modified by one thread at a time.  Unlike threads, processes don't share thesame address space. 3.  Threads areconsidered lightweight because they use far less resources than processes. 4.  Processes areindependent of each other.  Threads, since they share the same addressspace are interdependent, so caution must be takenso that differentthreads don't step on each other.  Thisis really another way of stating #2 above. 5.  A process can consistof multiple threads.

Thread

Advantages: ·        Much quicker to create a thread than a process. ·        Much quicker to switch between threads than to switchbetween processes. ·        Threads share data easily Consider few disadvantages too: ·        No security between threads. ·        One thread can stomp on another thread's data. ·        If one thread blocks, all threads in task block.
  • Doing background processing: Some tasks may not be time critical, but need to execute continuously.
  • Doing I/O work: I/O to disk or to network can have unpredictable delays.Threads allow you to ensure that I/O latency does not delay unrelated parts of your application.
  Less overhead to establish and terminate vs.a process:because verylittle memory copying is required (just the thread stack), threads are fasterto start than processes. To start a process, the whole process area must beduplicated for the new process copy to start. While some operating systems onlycopy memory once it is modified (copy-on-write), this is not universallyguaranteed. Faster task-switching: in many cases, it is faster for an operating systemto switch between threads for the active CPU task than it is to switch betweendifferent processes. The CPU caches and program context can be maintainedbetween threads in a process, rather than being reloaded as in the case ofswitching a CPU to a different process. Data sharing with other threads in aprocess: for tasks thatrequire sharing large amounts of data, the fact that threads all share aprocess’s memory pool is very beneficial. Not having separate copies means thatdifferent threads can read and modify a shared pool of memory easily. Whiledata sharing is possible with separate processes through shared memory andinter-process communication, this sharing is of an arms-length nature and isnot inherently built into the process model.

Disadvantage

  • Synchronization overhead of shared data:shared data that is modified requires special handling in the form of locks, mutexes and other primitives to ensure that data is not being read while written, nor written by multiple threads at the same time.
  • Shared process memory space:all threads in a process share the same memory space. If something goes wrong in one thread and causes data corruption or an access violation, then this affects and corrupts all the threads in that process. This is a special concern for cross-language environments where it is very easy to have subtle ABI interaction problems, such as Java-based web servers calling upon native libraries via the JNI (Java Native Interface) ABI.
  • Program debugging: multi-threaded programs present difficulties in finding and resolving bugs over and beyond the normal difficulties of debugging programs. Synchronization issues, non-deterministic timing and accidental data corruption all conspire to make debugging multi-threaded programs an order of magnitude more difficult than single-threaded programs.
 multipleprocesses in a browser  

8. pointer and reference

1.    A pointer can be re-assigned any numberof times while a reference can not be re-seated after binding. 2.    Pointers can point nowhere (NULL), whereas reference always refer to anobject. 3.    You can't take the address of areference like you can with pointers. 4.    There's no "referencearithmetics" (but you can take the address of an object pointed by areference and do pointer arithmetics on it as in &obj + 5). 5.A pointer has its own memory address and size onthe stack (4 bytes on x86), whereas a reference shares the same memory address(with the original variable)but also takesup some space on the stack. 6.You can have pointers to pointers to pointersoffering extra levels of indirection. Whereas references only offer one levelof indirection. 7 Pointers can iterate over an array, you can use ++ to go tothe next item that a pointer is pointing to, and + 4 to go to the 5th element.This is no matter what size the object is that the pointer points to. 8.A pointer needs to be dereferenced with * toaccess the memory location it points to, whereas a reference can be useddirectly. A pointer to a class/struct uses -> to access it's members whereasa reference uses a .. 9. A pointer is a variable that holds a memory address.Regardless of how a reference is implemented, a reference has the same memoryaddress as the item it references. 1 what is virtual method? inheritance ?  2 what's the difference between primary keyand foreign key?  3 what's the difference between copyconstructor and assignment operator? 4 what's the difference between process andthread ? 5 what's the difference between pointer andreference?  6 what is polymorphism(多态 virtual table, Polymorphism is when you can treat an object asa generic version of something, but when you access it, the code determineswhich exact type it is and calls the associated code  polymorphism isthe ability (in programming) to present the same interface for differingunderlying forms (data types). 面试官会追着问的很细,看你是否真的了解 7 what is static method?  A static variable is avariable that is shared across all instances of a class.   A static method is amethod that can be called on a class and usually does not require the class tobe instantiated. 8 what's the difference between TCP and UDP? Reliability: TCP is connection-oriented protocol.When a file or message send it will get delivered unless connections fails. Ifconnection lost, the server will request the lost part. There is no corruptionwhile transferring a message.       Reliability: UDP is connectionless protocol.When youa send a data or message, you don’t know if it’ll get there, it could get loston the way. There may be corruption while transferring a message. Ordered: If you send twomessages along a connection, one after the other, youknow the first message will get there first. You don’t have to worry about dataarriving in the wrong order.  Ordered: If you send two messages out, you don’t know whatorder they’ll arrive in i.e. no ordered Heavyweight: – when the low level parts of the TCP “stream” arrive in the wrongorder, resend requests have to be sent, and all the out of sequence parts haveto be put back together, so requires a bit of work to piece together.    Lightweight:No ordering of messages, no tracking connections, etc. It’s just fire andforget! This means it’s a lot quicker, and the network card / OS have to dovery little work to translate the data back from the packets. Streaming: Data is readas a “stream,” with nothing distinguishing where onepacket ends and another begins. There may be multiple packets per read call.        Datagrams:Packets are sent individually and are guaranteed to be whole if theyarrive. One packet per one read call. 10 what is singleton? 11 Do you know quick sort?  

Smart pointer 

A smart pointer is a class that wraps a'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointedto Reference counted pointersare very useful when the lifetime of your object is much more complicated, andis not tied directly to a particular section of code or to another object. Drawback the possibility of creating a dangling reference: Another possibility is creating circularreferences: ·        Use std::unique_ptr when you're not planning multiplereferences to the same object. For example, for a pointer which gets allocatedon entering some scope and de-allocated on exiting the scope. ·        Use std::shared_ptr when you do want to refer to yourobject from multiple places - and do not want it to be de-allocated until allthese references are themselves gone. ·        Use std::weak_ptr when you do want to refer to your object frommultiple places - for those references for which it's ok to ignore anddeallocate (so they'll just note the object is gone when you try todereference).   Oneof the simple smart-pointer type is std::auto_ptr (chapter20.4.5 of C++ standard), which allows to deallocate memory automatically whenit out of scope and which is more robust than simple pointer usage whenexceptions are thrown, although less flexible. Anotherconvenient type is boost::shared_ptr whichimplements reference counting and automatically deallocates memory when noreferences to object remains. This helps avoiding memory leaks and is easy touse to implement RAII.  

Exception and Error

Errors tend to signal theend of your application as you know it. It typically cannot be recovered fromand should cause your VM to exit. Catching them should not be done except topossibly log or display and appropriate message before exiting. Example:OutOfMemoryError -Not much you can do as your program can no longer run. Exceptions are oftenrecoverable and even when not, they generally just mean an attempted operationfailed, but your program can still carry on. Example:IllegalArgumentException -Passed invalid data to a method so that method call failed, but it does notaffect future operations.

Hashcode() and equals()

对象的hashcode再从Hash表中取这个对象。这样做的目的是提高取对象的效率。具体过程是这样:
1.new Object(),JVM根据这个对象的Hashcode,放入到对应的Hash表对应的Key,如果不同的对象确产生了相同的hash,也就是发生了Hash key相同导致冲突的情况,那么就在这个Hash key的地方产生一个链表,将所有产生相同hashcode的对象放到这个单链表上去,串在一起。
2.比较两个对象的时候,首先根据他们的hashcodehash表中找他的对象,当两个对象的hashcode相同,那么就是说他们这两个对象放在Hash表中的同一个key,那么他们一定在这个key上的链表上。那么此时就只能根据Objectequal方法来比较这个对象是否equal。当两个对象的hashcode不同的话,肯定他们不能equal. 实现一个自己的Map,首先考虑的是如何优化Hash算法,因为自己的Map应该会对应具体的类,可以根据自己类的属性,找出一种能提高查询效率的方法.如上一个例子.相当于 hashcode能为数组提供8个链路,这样速度大大提升.紧记0~8存储例子。 HashMap的数据结构是数组和链表的结合,所以我们当然希望这个HashMap里面的 元素位置尽量的分布均匀些,尽量使得每个位置上的元素数量只有一个,那么当我们用hash算法求得这个位置的时候,马上就可以知道对应位置的元素就是我们要的,而不用再去遍历链表,这样就大大优化了查询的效率。  

HashMap

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls

Sleep() VS wait()

sleep()方法 sleep()使当前线程进入停滞状态(阻塞当前线程),让出CUP的使用、目的是不让当前线程独自霸占该进程所获的CPU资源,以留一定时间给其他线程执行的机会;
sleep()Thread类的Static(静态)的方法;因此他不能改变对象的机锁,所以当在一个Synchronized块中调用Sleep()方法是,线程虽然休眠了,但是对象的机锁并木有被释放,其他线程无法访问这个对象(即使睡着也持有对象锁)。
  在sleep()休眠时间期满后,该线程不一定会立即执行,这是因为其它线程可能正在运行而且没有被调度为放弃执行,除非此线程具有更高的优先级。 
  wait()方法 wait()方法是Object类里的方法;当一个线程执行到wait()方法时,它就进入到一个和该对象相关的等待池中,同时失去(释放)了对象的机锁(暂时失去机锁,wait(long timeout)超时时间到后还需要返还对象锁);其他线程可以访问;
wait()使用notify或者notifyAlll或者指定睡眠时间来唤醒当前等待池中的线程。
wiat()必须放在synchronized block中,否则会在program runtime时扔出”java.lang.IllegalMonitorStateException“异常。

difference btween C and C++ 

1C is a structuralor procedural programming language. C++ is an objectoriented programming language. 2Functions are thefundamental building blocks. Objects are thefundamental building blocks. 3In C, the data isnot secured. Data is hidden andcan’t be accessed by external functions. 4C uses scanf()and printf() function for standard input and output. C++ usescin>> and cout<< for standard input and output. 5. C doesn’tsupport exception handling directly. Can be done by using some other functions. C++ supportsexception handling. Done by using try and catch block. 6. Features likefunction overloading and operator overloading is not present. C++ supportsfunction overloading and operator overloading. 6.     mallocand free vs newand delete;

diffrence between Java and C++

Everything must be in a class. There are no global functions orglobal data. If you want the equivalent of globals, make static methods andstatic data within a class. There are nostructs or enumerations or unions, only classes. Write once, run anywhere, butit's still much easier than writing a C++ cross-platform code. C++ supports multiple class inheritance, while Java only givesyou a single class inheritance, but solves the multiplicity via interfaces. C++ has got a pointers, and can directly manipulate/violate thememory addresses. At compilation time JavaSource code converts into byte code .The interpreter execute this byte code atrun timeand gives output .Java is interpreted for themost part and hence platform independent. C++ run and compile using compilerwhich converts source code into machine level languages so c++ is plate fromdependents Java is platform independent language butc++ is depends upon operating system machine etc. C++ source can be platform independent(and can work on a lot more, especially embedeed, platforms), although thegenerated objects are generally platofrom dependent but there is clang forllvmwhich doesn't have this restriction. Java uses compiler andinterpreter both and in c++ their is only compiler C++ supports operatoroverloading multiple inheritance but java does not. C++ is more nearer to hardware then Java Everything (except fundamental types) is anobject in Java (Single root hierarchy as everything gets derived from java.lang.Object). Java does is a similar to C++ but not haveall the complicated aspects of C++ (ex: Pointers, templates, unions, operatoroverloading, structures etc..) Java does not support conditional compile(#ifdef/#ifndef type). Thread support is built-in Java but not inC++. C++11, the most recent iteration of the C++ programming language does haveThread support though. Internet support is built-in Java but notin C++. However c++ has support for socket programming which can be used. Java does not support header file, includelibrary files just like C++ .Java use import to include different Classes andmethods. Java does not support default argumentslike C++. There is no scoperesolution operator :: in Java. It has . using which we can qualify classes withthe namespace they came from. There is no goto statement in Java. Exception and Auto Garbage Collector handling in Javais different because there are no destructors into Java. Java has methodoverloading, but no operator overloading just like c++. The String class does use the + and +=operators to concatenate strings and String expressions use automatic typeconversion, Java is pass-by-value. Java does not supportunsigned integer  

private constructor:

1.    The constructor can only be accessedfrom static factory method inside the class itself.Singleton can also belong to this category. 2.