昨天和师兄讨论,单例的最好实现到底是什么
果然一家之言有时候还是不可尽信:
volatile对双重检查锁定的影响和 IoDH 对单例来说都是个不错的实现,此外还有枚举。师兄提到IoDH的内部类可能会导致加载失败,万分之一的几率会使单例加载失败。一个单例都这么多东西搞。
关于并发中Java锁的分析。
写了冉教授的爬虫项目,现在看来做这个没什么用的项目真实浪费时间浪费精力,嗨,罢了,争取这两天搞掂。
就在刚刚,简陋地完成了项目的任务,突然想复习一下以前看过的百田的笔试题目:
1. String ,StringBuffer StringBuilder之间的差别
以下在博文中写的都是并非三者间的完整差别,只是我此前并不知道也不了解的差别:
String:除了是immutable也是线程安全,但是String 的 substring 方法有发生内存leak(泄露)的可能,中文博文,英文博文,解决方法是 new String(str.substring(begin,end));在原substring中新建一个string。
StringBuffer 与 String:个人理解的最大却别是 immutable与mutable,对String使用“+”每次都会返回一个新的String,而StringBuffer和StringBuilder则在原来的基础上更改,而StringBuffer是较旧的,StringBuilder是java5以后才出现的,同时StringBuffer是thread-safe,StringB
byte[] d = a.getBytes();
System.out.println(Arrays.toString(d));
uilder不是,所以应该适当选用,如果是做算法题目的话当然是StringBuilder。StringBuffer和StringBuilder的api是非常相似的。
另外,上个Javarevisited都要翻墙,我大天朝这是怎么了
1. String是immutable的,在内存堆或者常量池中会存在很长一段时间,gc才会回收它,所以不安全,任何对String set的操作都没用,因为它会返回一个new string,但是就是只能被动等待gc回收,但是char[] 的话可以自己set为0000000,由程序员把握。
2. Java推荐使用JPasswordField的getPassword() 返回 char[] ,java team 都这么推荐了。
3. 如果你一不小心答应了string,那是答应了整个string,密码明文显示,但是如果答应 char[] 答应的是内存地址,除非使用 Arrays.toString(charArrayName),就这角度上说安全性都比String要好。
下面是将String转为char[]
String a = "hello,world";
char[] b = a.toCharArray();
System.out.println(Arrays.toString(b));
另外String的api有必要记忆一下:
Modifier and Type | Method and Description |
char | charAt(int index) |
int | codePointAt(int index) returns the character unicode code point |
int | codePointBefore(int index) |
int | codePointCount(int beginIndex, int endIndex) what? |
int | compareTo(String anotherString) lexicographically 字典顺序排序 |
int | compareToIgnoreCase(String str) |
String | concat(String str) |
boolean | contains(CharSequence s) |
boolean | contentEquals(CharSequence cs) |
boolean | contentEquals(StringBuffer sb) 不明白,StringBuffer实现了CharSequence接口上面那个不就够了吗 |
static String | copyValueOf(char[] data) returns a String that represents the charracter sequence in the array specified |
static String | copyValueOf(char[] data ,int offset, int count) |
boolean | endsWith(String suffix) |
boolean | equals(Object anObject) |
boolean | equalsIgnoreCase(String anotherString) |
static String | format(Locale l ,String format, Object... args) what? |
static String | format(String format, Object... args) what? |
byte[] | getBytes() |
byte[] | getBytes(Charset charset) |
测试代码:
byte[] d = a.getBytes();
System.out.println(Arrays.toString(d));
结果:
输出unicode编码。