Java Interview (ii)

Source: Internet
Author: User
Tags comparable

1 Synchronous Method VS Synchronous code block:

In Java, each object has a lock, and the thread acquires the lock on the object with synchronized.

Non-static synchronization method: A lock is a lock on an object of a class.

Static Synchronization method: The lock is the class itself.

Synchronization method Block: The lock is optional. So we can control it more precisely. Finer granularity allows for more precise control of object locks.

2 ensure n threads can access n resources without deadlock?

Specifies the order in which the resource gets fetched. All threads request resources in the same order.

3 Java Collection Framework interface

Collection: Represents a group of objects.

Set:

List:

MAP:

4 Why does the collection class not implement the cloneable and serializable interfaces?

The elements in the collection should be implemented by themselves, defining their own behavior.

5 What is an iterator (Iterator)?

It allows the traversal of a data structure for a sequence type to be separated from the object being traversed, that is, we don't have to care what the underlying structure of the sequence looks like. As soon as you get this object, you can iterate through the inside of the object using an iterator.

Main method: Hasnext ()/Next ()/remove (after deletion, point to next)

Iterator Benefits: Provides a unified iterative approach, can provide different iterative methods in the case of transparent to the customer, and fast failure mechanism to prevent the unsafe operation of iteration under multi-thread.

6 Quick Failure && Security failure:

(Note: The modification of the following set refers to the change of the collection structure, the addition, deletion of nodes, the modification of the contents of a node's objects is not considered a change in the collection structure.) )

Fast Failure (Fail-fast):

When traversing a collection with an iterator, other threads modify the contents of the collection (increment, delete)during the traversal, then

Throws an exception concurrentmodificationexception. The iterator accesses the elements of the collection directly while traversing, and uses a Modcount variable during traversal. When a collection is traversed, the value of Modcount is changed if the content changes. Every time an iterator Hasnext ()/next () traverses an element, it detects the Modcount and throws an exception if it is changed. the collection in the Java.util package is fast-failing and cannot occur concurrently with multithreading.

Security Failure (Fail-Safe):

If you add/delete/change to map while the iterator is traversing Concurrenthashmap, no exception is thrown. However, this can lead to inconsistent issues. A collection container using the security failure mechanism, which is not accessed directly on the collection content, but first replicates the original collection content and iterates over the copied collection. The downside is that you can't access the modified content,

The containers under the Java.util.concurrent package are safe and fail , and can be used concurrently in multiple threads and concurrently modified.

The security failure iterator is modified in the iteration and does not throw any exceptions because it iterates over the cloned object of the collection, so any structural modifications to the original collection object are ignored by the iterator, but there are drawbacks to this type of iterator, one of which is that it does not guarantee that you will get the latest data when iterating. Because any modifications to the collection after the iterator is created are not updated in that iterator, there is also a disadvantage that creating a cloned object can add a burden to both time and memory.

7 Iterator and Listiterator differences

Iterator can be used to traverse set,map and lists, but listitrator can only be used to traverse the list.

Iterator can only traverse forward (Hasnext (), Next ()) to the collection. Listiterator is a bidirectional traversal.

Listiterator implements the iterator interface and includes other functions, such as adding elements, replacing elements, and getting the index of the previous and subsequent elements.

8 How the HashMap works

The key-value pair forms the stored element. A hash function is required, using the hashcode () and Equals () methods to add to the collection and retrieve the elements.

Put (key, value): Calculates the hash value of the key, and then stores the key-value pairs on the appropriate index in the collection. Entry is stored in LinkedList, so if there is a entry, it uses the Equals () method to check whether the passed key already exists, and if it does, it overwrites value and if it does not, it creates a new entry and then saves it.

Get (Key): The first is to use Hashcode to find the bucket, and then key,equals (), to determine whether equal.

Important features are capacity (the default initial value is 32), the load factor (default is 0.75), the threshold is the load factor multiplied by the capacity, and if it is greater than the threshold, it expands. Expansion limit. It is recommended to set the initial value if you know the number of elements at the beginning.

Capacity: The number of barrels.

Load factor: How many barrels are occupied.

9 HashMap VS Hashtable

All implement the map interface, very similar. There are different points:

The key and value of HashMap is null,hasttable does not allow the key or value to be null.

HashMap is not synchronous (for single-threaded, fast-failing), Hashtable (for multithreading) is synchronous.

HashMap provides a collection of keys, while Hashtable provides an enumeration of the keys.

Hashtable is a legacy class.

What is the difference between a 10 array and a list (ArrayList)? Their own applications?

Array: can hold base type + object type; list: only object type (because the elements in the list must inherit from object).

An array of fixed size; ArrayList is dynamically changing.

ArrayList offers a number of methods: AddAll (), RemoveAll (), iterator (), and so on.

For basic types, the collection uses auto-boxing to reduce the amount of code, but this is slower when dealing with fixed-size base data types.

ArrayList VS LinkedList

The list interface is implemented.

ArrayList the bottom layer is an array. Elements can be randomly accessed with an O (1) time complexity.

LinkedList: Data is stored as a list of elements, linked lists. The time complexity of the lookup is 0 (n), but inserted, added, and deleted faster.

LinkedList more memory because the pointer is to be stored.

Comparable and Comparator?

Implements the comparable, indicating that elements can be compared and sorted by sort. Comparator as an algorithm implementation, separating the algorithm from the data.

Using Comparator is the strategy mode (strategy design pattern), which does not change the object itself, but uses a policy object (strategy object) to change its behavior.

Comparable interface: Contains only one CompareTo () method, which can be sorted.

Comparator interface: Contains two methods of compare () and Equals ().

The two usages are different: for example, the elements in the collection can implement comparable on their own, so they can be sorted by Collections.sort () call, and if you want to define an extra sorting method, you can implement the comparator interface. Collections.sort () Another overloaded method can receive a compareator.

Best Practices for Java collection classes

Select the correct choice to use as needed. For example: fixed element size, known in advance, with Array instead of ArrayList

For some containers (HASHMAP): If you know the capacity, you can advance to an initial capacity, avoid the expansion, and then Hasi performance loss.

For type safety, readability and robustness are always used generics, generics can avoid classcastexception-

Using the invariant Class (immutable Class) provided by the JDK as the key to the map avoids implementing hashcode () and

Equals () method.

The interface is better than the implementation when programming.

If the underlying collection is actually empty, return the collection or array with a length of 0, and do not return NULL.

Java Priority queue

The highest priority is given each time the team is out. is implemented with a large top heap . To provide a comparator comparator, otherwise be arranged in natural order.

queue<test> priqueue = new priorityqueue<test> (11,ORDERISDN); Specify a Comparator

The default queue size is 11

Test T1 = new Test ("T1", 1);

Test t3 = new Test ("T3", 3);

Priqueue.add (T3);

Based on the priority heap unbounded queue, its elements are sorted in natural order and can provide a comparator when created. Null values are not allowed. It is not thread-safe, and the time complexity of the queue and the out pair is log (n).

15 What is thread safety?

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe.

For example a ArrayList class, when adding an element, it may have two steps to complete: 1. This element is stored in the location of Items[size]; 2. Increase the value of Size. In the case of single-threaded runs, if Size = 0, after adding an element, this element is at position 0, and size=1;

In the case of multithreading, such as having two threads, thread A first stores the elements in position 0. However, when CPU scheduler thread a pauses, thread B gets the chance to run. Thread B also adds elements to this ArrayList, since Size is still equal to 0 (note that we assume that adding an element is a two-step process, and thread A just completes step 1), so thread B also stores the element in position 0. Then both thread A and thread B continue to run, increasing the value of Size.

Well, now let's take a look at ArrayList, where the element is actually only one, stored in position 0, and Size equals 2. This is "thread insecure".
How to do thread safety:
Four Ways to sychronized keywords

1. Sychronized method () {}//Synchronization methods

2. sychronized (objectreference) {/*block*/}//sync block

3. Static Synchronized Method () {}//Static synchronization methods

4. sychronized (Classname.class)//Specify synchronization class

where 1 and 2 represent locks on the current object, that is, an object is a lock, and 3 and 4 represent the lock class, the lock of this class. Note that sychronized method () is not a lock function, but a lock object , that is, if there are two methods in this class that are sychronized, then as long as there are two threads sharing a reference of that class, Each call to one of these two methods, whether or not the same method, will be used to synchronize with this object lock.
Note: Long and double are simple types in two special knock: Java read them to read two times, so need to synchronize.

16 How to weigh an unordered array or an ordered array

The time complexity of an ordered array lookup is O (logn), but the time complexity of the insert operation is O (n).

The unordered is O (n), but the time complexity of the insertion is O (1).

In Java, whether int is type-safe.

The assignment of Int is atomic, but i++ is not.

HashSet VS TreeSet

HashSet elements are unordered, put up to a null value, add (), remove (), contains (), the complexity of these methods is O (1)

TreeSet: A tree-structured implementation in which elements are ordered and cannot be placed into null values. ADD (), remove (), contains () complexity is log (n).

  

Java Interview (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.