String,StringBuffer,StringBuilder,char[] & volatile对双重检查锁定的影响

昨天和师兄讨论,单例的最好实现到底是什么

果然一家之言有时候还是不可尽信:

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都要翻墙,我大天朝这是怎么了快哭了

为什么 char[] 比String更适合储存密码

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 TypeMethod and Description
charcharAt(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)
Stringconcat(String str)
booleancontains(CharSequence s)
booleancontentEquals(CharSequence cs)
booleancontentEquals(StringBuffer sb)
不明白,StringBuffer实现了CharSequence接口上面那个不就够了吗
static StringcopyValueOf(char[] data) 
returns a String that represents the charracter sequence in the array specified
static StringcopyValueOf(char[] data ,int offset, int count)
booleanendsWith(String suffix)
booleanequals(Object anObject)
booleanequalsIgnoreCase(String anotherString)
static Stringformat(Locale l ,String format, Object... args)
what?
static Stringformat(String format, Object... args)
what?
byte[]getBytes()
byte[]getBytes(Charset charset)

测试代码:

		byte[] d = a.getBytes();
		System.out.println(Arrays.toString(d));

结果:


输出unicode编码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值