AlphaWang.com

Alpha's Programming Notes | 一个程序员的日常

What's String.intern()

Java语言中有8种基本类型和一种比较特殊的类型String。为了使这些类型在运行过程中速度更快,更节省内存,都提供了一种常量池的概念。常量池就类似一个Java系统级别提供的缓存。

其中8种基本类型的常量池都是系统协调的,而String类型的常量池比较特殊。它的主要使用方法有两种:

  • 直接使用双引号声明出来的String对象会直接存储在常量池中。
  • 如果不是用双引号声明的String对象,可以使用String.intern()方法。intern方法会从字符串常量池中查询当前字符串是否存在,若不存在就会将当前字符串放入常量池中

How to Implement a HashMap

作为一个Java开发民工,对HashMap可以说是经常使用的,不过要是想更好地使用它,还是需要了解其内部实现原理的。当了解了实现原理后,自己实现一个HashMap也就不难了。

How to Pass POJO Array to Spring MVC Controller

问题

最近遇到个需求,需要将一个对象数组从前端用ajax传递给后端的Spring MVC Controller,例如传递如下数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  products: [
    {
      category: 100,
      name: 'iPad',
      attributes: {
        volume: '32G',
        color: 'white'
      }
    },
    {
      category: 200,
      name: 'xx t-shirt',
      attributes: {
        size: 'M',
        color: 'red'
      }
    }
    
  ],
  locale: 'zh_CN'
}  

Integrate Octopress With Flickr

Octopress Blog有一个很酷的插件,可以将Flickr中的某个图片插入到你的博文中。像这样:
{\% flickr_image 15313566521 o \%}

还可以把Flickr某个相册中的所有图片都插入进来,像这样

Utility Classes Are Evil

This post is a summary of this artical and this one.

What’s Utility Classes

A utility class is a class filled with static methods. It is usually used to isolate a “useful” algorithm.

StringUtils, IOUtils, FileUtils from Apache Commons; Iterables and Iterators from Guava, and Files from JDK7 are perfect examples of utility classes.

Why Utility Classes

If you have two classes A and B, and have a method f() that both must use, then the most naive approach is to repeat the function as a method in both classes. However, this violates the Don’t repeat yourself (DRY) approach to programming.

The most natural solution is inheritance, but it’s not always beneficial for A and B to be subclasses of some parent class. In my case, A was already a subclass of another class, while B was not. There was no way to make A and B subclasses of a parent class without breaking that other relationship.

The alternative is to define the utility class: a public static class that sits in the global namespace, awaiting anyone to “borrow” them.

They are not bad in themselves, but they do imply relationships between your data that are not explicitly defined. Also, if your static class has any static variables, then A and B never really know what they’re getting into when they use it.

Make Mac Terminal Console / iTerm Colorful

Neither Terminal or iTerm on Mac is white/black color by default, which looks tedious. What if different entries shown in different colors?
Fortunately, we can do this just by writing a configuration file, then the terminal console or iTerm can look like this:

iterm icon