Java Collections

What are different ways to iterate over a list?

List<String> strList = new ArrayList<>();
//using for-each loop
for(String obj : strList){
    System.out.println(obj);
}
//using iterator
Iterator<String> it = strList.iterator();
while(it.hasNext()){
    String obj = it.next();
    System.out.println(obj);
}

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException

What do you understand by iterator fail-fast property?

Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are modifications found, it throws ConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.

How HashMap works?

HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and use hashCode() and equals() method in put and get methods.

When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value, else it creates a new entry and store this key-value entry.

If o1.equals(o2), then o1.hashCode() == o2.hashCode() should always be true

If o1.hashCode() == o2.hashCode(), it doesn't mean that o1.equals(o2) will be true

What is difference between HashMap and HashTable?

  • HashMap allows null key and values whereas HashTable doesn't allow null key and values
  • HashTable is synchronized but HashMap is not synchronized. So HashMap is better for single threaded environment, HashTable is suitable for multi-threaded environment

How to decide between HashMap and TreeMap?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative.

What is difference between ArrayList and LinkedList?

  • ArrayList is an index based data structure backed by Array, so it provides random access to its elements with performance as O(1) whereas performance in LinkedList is O(n)
  • Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle
  • LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements

What is BlockingQueue?

java.util.concurrent.BlockingQueueis a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

2015/10/25

What is HttpOnly?

HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie.

If the HttpOnly flag is included in the HTTP response header, the cookie cannot be accessed through client side script.

If a browser that supports HttpOnly detects a cookie containing the HttpOnly flag, and client side script code attempts to read the cookie, the browser returns an empty string as the result.

Cookie cookie = getMyCookie("myCookieName");
cookie.setHttpOnly(true);
2015/10/25

Freemarker Error Handling

The possible exception

The exception that can occur regarding Freemarker could be classified like this:

  • Exceptions occurring when you configure Freemarker: Typically you configure Freemarker only once in your application, when your application initializes itself.
  • Exceptions occurring when loading and parsing templates: When you call Configuration.getTemplate(...), Freemarker has to load the template file into the memory and parse it. During this, two kinds of exceptions can occur:

    • IOException because the template file was not found, or other I/O problem occurred while trying to read it (you have no right to read the file, or there are disk errors).
    • freemarker.core.ParseException because the template file is syntactically incorrrect according the rules of the FTL language. This exception is an IOException subclass.
  • Exception occurring when executing templates. Two kinds of exceptions can occur:

    • IOException because there was an error when trying to write into the output writer.
    • freemarker.template.TemplatException because other problem occurred while executing the template. For example, a frequent error is when a template refers to a variable which is not existing. Be default, when a TemplatException occurs, Freemarker prints the FTL error message and the statck trace to the output writer with plain text format, and then aborts the template execution by re-throwing the TemplatException, which then you can catch as Template.process(...) throws it.

      class MyTemplateExceptionHandler implements TemplateExceptionHandler {
          public void handleTemplateException(TemplateException te, Environment env, java.io.Writer out)
                  throws TemplateException {
              try {
                  out.write("[ERROR: " + te.getMessage() + "]");
              } catch (IOException e) {
                  throw new TemplateException("Failed to print error message. Cause: " + e, env);
              }
          }
      }
      
      ...
      
      cfg.setTemplateExceptionHandler(new MyTemplateExceptionHandler());
      

Handling missing values

${mouse!"No mouse."}
<#assign mouse="Jerry">
${mouse!"No mouse."}

The output will be:

No mouse.
Jerry

product.color!"red"

This will handle if color is missing inside product, but will not handle if product is missing. That is, the product variable itself must exist, otherwise the template processing will die with error.

(product.color)!"red"

This will handle if product.color is missing. That is, if product is missing, or product exists but it does not contain color, the result will be red, and no error will occur.

The important difference between this and the previous example is that when surrounded with parentheses, it is allowed for any component of the expression to be undefined, while without parentheses only the last component of the expression is allowed to be undefined.

Missing value test operator
<#if mouse??>
Mouse found
</#if>
2015/10/25

Levenshtein Distance"

2015/10/25

How to use bloom filter to build a large in memory cache in Java"

模拟查找文件29的过程:

  • 根据根节点指针找到文件目录的根磁盘块1,将其中的信息导入内存。【磁盘IO操作1次】
  • 此时内存中有文件名17、35和三个存储其他磁盘页面地址的数据。根据算法我们发现:17<29<35,因此我们找到指针p2
  • 根据p2指针,我们定位到磁盘块3,并将其中的信息导入内存【磁盘IO操作2次】
  • 此时内存中有两个文件名26、30和三个存储其他磁盘页面地址的数据。根据算法我们发现:26<29<30,因此我们找到指针p2
  • 根据p2指针,我们定位到磁盘块8,并将其中的信息导入内存。【磁盘IO操作3次】
  • 此时内存中有两个文件名28、29.根据算法我们查找到文件名29,并定位了该文件内存的磁盘地址。
2015/10/25