首页 > 技术文章 > Java(jdk1.7) 陷阱

DeeFOX 2014-02-14 11:24 原文

String[] strA = new String[4];
for(int i=0; i<4; i++) {
    strA[i] = String.valueOf(i);
}
strA[0] = strA[2];
strA[2] = null;

上述代码以后,strA[0]会等於多少?

陷阱:strA[0],strA[2] 都等于 null

答案:等于2

 

===================================

"举报| | 回复◆◆ 同时转发到我的微博 评论".replace("举报| | 回复", "")  =="举报| | 回复◆◆ 同时转发到我的微博 评论".replaceAll("举报| | 回复", "")

陷阱:String.replace和replaceAll的功能貌似只是在覆盖的数量上不一样而已

答案:但其实不然!repalce不会去解析字符串中的正则表达式字符比如说:“|”等,但是replaceAll则会解析匹配正则表达式(也有可能是我的理解错误,replaceall是最小匹配每一个,而replace则是一次最大匹配!)

  上面程序分别获得是:

    ◆◆ 同时转发到我的微博 评论
    ||回复◆◆同时转发到我的微博评论

 

===================================

10个有关String的面试问题

  1. 如何比较两个字符串?使用“==”还是equals()方法?
  2. 为什么针对安全保密高的信息,char[]比String更好?
  3. 我们可以针对字符串使用switch条件语句吗?
  4. 如何将字符串转化成int?
  5. 如何将字符串用空白字符分割开?
  6. substring()方法到底做了什么?
  7. String vs StringBuilder vs StringBuffer
  8. 如何重复一个字符串
  9. 如何将字符串转换成时间
  10. 如何计算一个字符串某个字符的出现次数?

 

===================================

LinkedBlockingQueue vs ConcurrentLinkedQueue

For a producer/consumer thread, I'm not sure that ConcurrentLinkedQueue is even a reasonable option - it doesn't implement BlockingQueue, which is the fundamental interface for producer/consumer queues IMO. You'd have to call poll(), wait a bit if you hadn't found anything, and then poll again etc... leading to delays when a new item comes in, and inefficiencies when it's empty (due to waking up unnecessarily from sleeps).

From the docs for BlockingQueue:

BlockingQueue implementations are designed to be used primarily for producer-consumer queues

I know it doesn't strictly say that only blocking queues should be used for producer-consumer queues, but even so...

推荐阅读