2014年5月13日星期二

char, int, string相互转换

char to int:
Character.getNumericValue(char c)

String to int:
Integer.parseInt(String s)

int to StringBuilder

s.append(int i);

string to char:

s.charAt();

char to string:

You can use Character.toString(char). Note that this method simply returns a call to String.valueOf(char), which also works.
As others have noted, string concatenation works as a shortcut as well:
String s = "" + 's';
But this compiles down to:
String s = new StringBuilder().append("").append('s').toString();
which is less efficient because the StringBuilder is backed by a char[] (over-allocated by StringBuilder() to 16), only for that array to be defensively copied by the resulting String.
String.valueOf(char) "gets in the back door" by wrapping the char in a single-element array and passing it to the package private constructor String(int, int, char[]), which avoids the array copy.

String stringValueOf = String.valueOf('c');

String characterToString = Character.toString('c');

String characterObjectToString = new Character('c').toString();

String concatBlankString = 'c' + "";

String fromCharArray = new String(new char[]{x});

2014年5月7日星期三

ArrayList 用法

When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.
One way to add ten elements to the array list is by using a loop:
for (int i = 0; i < 10; i++) {
  arr.add(0);
}
Having done this, you can now modify elements at indices 0..9.

So you can only add elements first after you create ArrayList. You can't use Set to change value because it is empty at beginning.