[Java基础] Top 10 questions of Java Strings

API: java.lang.String

虽然直接看原文就可以了...不过挺常用的...因此收藏一下. 其它关于字符串的内容也添加到这篇中.

原文

1、How to compare strings? Use == or use equals()?

In brief, == tests if references are equal and equals() tests if values are equal. Unless you want to check if two strings are the same object, you should always use equals().

【考虑是比较引用还是比较值】

It would be better if you know the concept of string interning.

另一个问题 —— Why string is immutable in Java ?

  1. Requirement of String Pool
  2. Allow String to Cache its Hashcode【保证相同字符串的Hashcode是一样的】
  3. Security

==只是单纯比较是不是同一个对象, 而equals()才是比较对象的值. 因此有时需要为对象override equals()方法.】

-----【补充】-----

全面理解Java中的String数据类型

new String()new String("")都是申明一个新的空字符串, 是空串不是null

常量池(constant pool)指的是在编译期被确定, 并被保存在已编译的.class文件中的一些数据. 它包括了关于类、方法、接口等中的常量, 也包括字符串常量.

String中intern的方法

String a = new String("ab");
String b = new String("ab");
String c = "ab";
String d = "a" + "b";
String e = "b";
String f = "a" + e;

System.out.println(c == d); // true
System.out.println(b.intern() == a); // false
System.out.println(b.intern() == c); // true
System.out.println(b.intern() == d); // true
System.out.println(b.intern() == f); // false
System.out.println(b.intern() == a.intern()); // true

2、Why is char[] preferred over String for security sensitive information?

Strings are immutable, which means once they are created, they will stay unchanged until Garbage Collector kicks in. With an array, you can explicitly change its elements. In this way, security sensitive information(e.g. password) will not be present anywhere in the system.

3、Can we use string for switch statement?

Yes to version 7. From JDK 7, we can use string as switch condition. Before version 6, we can not use string as switch condition.

// java 7 only!
switch (str.toLowerCase()) {
    case "a":
        value = 1;
        break;
    case "b":
        value = 2;
        break;
}

【一般情况是整型或能转成整型的...】

4、How to convert string to int?

int n = Integer.parseInt("10");

Simple, but so frequently used and sometimes ignored.【确实常用】

5、How to split a string with white space characters?

We can simple do split using regular expression. \s stands for white space characters such as " ", "\t", "\r", "\n".

String[] strArray = aString.split("\\s+");

6、What substring() method really does?【注意JDK6与JDK7实现上的区别】

In JDK 6, the substring() method gives a window to an array of chars which represents the existing String, but do not create a new one. To create a new string represented by a new char array, you can do add an empty string like the following:

str.substring(m, n) + ""

This will create a new char array that represents the new string. The above approach sometimes can make your code faster, because Garbage Collector can collect the unused large string and keep only the sub string.

In Oracle JDK 7, substring() creates a new char array, not uses the existing one. Check out the diagram for showing substring() difference between JDK 6 and JDK 7.

7、String vs StringBuilder vs StringBuffer

String vs StringBuilder: StringBuilder is mutable【可变的】, which means you can modify it after its creation.

StringBuilder vs StringBuffer: StringBuffer is synchronized【同步的】, which means it is thread-safe【线程安全】 but slower than StringBuilder.

【HashTable与HashMap的区别, HashTable是同步的, 线程安全的】

8、How to repeat a string?

In Python, we can just multiple a number to repeat a string【在Python中"abcd"*3】. In Java, we can use the repeat() method of StringUtils from Apache Commons Lang package.

String str = "abcd";
String repeated = StringUtils.repeat(str, 3);
//abcdabcdabcd

9、How to convert string to date?

String str = "Sep 17, 2013";
Date date = new SimpleDateFormat("MMMM d, yy", Locale.ENGLISH).parse(str);
System.out.println(date);
//Tue Sep 17 00:00:00 EDT 2013

10、How to count # of occurrences of a character in a string?

Use StringUtils from apache commons lang.

int n = StringUtils.countMatches("11112222", "1");
System.out.println(n);

【Python中, "11112222".count("1")

One more

Do you know How to detect if a string contains only uppercase letter?【这篇感觉没啥意义】

Use java.lang.Character#isUpperCase() and #isLetter() instead of the magic numbers.

【最优的一般是使用内置的方法】