Morgan Stanley(摩根斯坦利)筆試加電面試題大全
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.
20.sql注入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: 在該模式裡可能有多個生產者,多個消費者,生產者和消費者都有獨立的執行緒。其中最關鍵的是放置資料的緩衝區,生產者和消費者在操作緩衝區時都必須同步,生產者往緩衝區放置資料時,如果發現緩衝區已滿則等待,消費者從緩衝區取資料時如果發現緩衝區沒有資料,也必須等待。當程式裡有多個生產者角色或者多個消費者角色操作同一個共享資料時,適合用生產者消費者模式。比如下載模組,通常會有多個下載任務執行緒(消費者角色),使用者點選下載按鈕時產生下載任務(生產者角色),它們會共享任務佇列。
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
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.
- One is to minimize the number of objects passed to the old area;
- 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.比較兩個物件的時候,首先根據他們的hashcode去hash表中找他的物件,當兩個物件的hashcode相同,那麼就是說他們這兩個物件放在Hash表中的同一個key上,那麼他們一定在這個key上的連結串列上。那麼此時就只能根據Object的equal方法來比較這個物件是否equal。當兩個物件的hashcode不同的話,肯定他們不能equal.
實現一個自己的Map時,首先考慮的是如何優化Hash演算法,因為自己的Map應該會對應具體的類,可以根據自己類的屬性,找出一種能提高查詢效率的方法.如上一個例子.相當於 hashcode能為陣列提供8個鏈路,這樣速度大大提升.緊記0~8儲存例子。
HashMap的資料結構是陣列和連結串列的結合,所以我們當然希望這個HashMap裡面的元素位置儘量的分佈均勻些,儘量使得每個位置上的元素數量只有一個,那麼當我們用hash演算法求得這個位置的時候,馬上就可以知道對應位置的元素就是我們要的,而不用再去遍歷連結串列,這樣就大大優化了查詢的效率。
HashMap
The HashMapclass 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 simila