ここまで、charとbyteの違い、char配列とStringの違いを中心に述べてきましたが、 Stringとchar配列、byte配列とは、相互に関わりあっています。 JavaのString クラスには、charやbyteの配列から文字列オブジェクトを生成する コンストラクタや、逆に、文字列オブジェクトを、charやbyteの配列に変換する メソッドが豊富に用意されています。
// char配列からStringを生成するコンストラクタ
public String(char value[]) {
this.count = value.length;
this.value = new char[count];
System.arraycopy(value, 0, this.value, 0, count);
}
// char配列の部分列からStringを生成するコンストラクタ
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
// byte配列からStringを生成。デフォールトのコンバータを利用。
public String(byte bytes[]) {
this(bytes, 0, bytes.length, ByteToCharConverter.getDefault());
}
// 先のコンストラクタの基礎にある、基本的なコンストラクタ。
private String(byte bytes[], int offset, int length,
ByteToCharConverter btc)
{
int estCount = btc.getMaxCharsPerByte() * length;
value = new char[estCount];
try {
count = btc.convert(bytes, offset, offset+length,
value, 0, estCount);
count += btc.flush(value, btc.nextCharIndex(), estCount);
}
catch (CharConversionException x) {
count = btc.nextCharIndex();
}
if (count < estCount) {
// A multi-byte format was used: Trim the char array.
char[] trimValue = new char[count];
System.arraycopy(value, 0, trimValue, 0, count);
value = trimValue;
}
}
// 文字列の内容をchar配列に代入するメソッド。
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > count) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, offset + srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
// 文字列からbyte配列を作るメソッド。デフォールトのコンバータを利用。
public byte[] getBytes() {
return getBytes(CharToByteConverter.getDefault());
}
// 先のコンストラクタの基礎にある、基本的なコンストラクタ。
private byte[] getBytes(CharToByteConverter ctb) {
ctb.reset();
int estLength = ctb.getMaxBytesPerChar() * count;
byte[] result = new byte[estLength];
int length;
try {
length = ctb.convert(value, offset, offset + count,
result, 0, estLength);
length += ctb.flush(result, ctb.nextByteIndex(), estLength);
} catch (CharConversionException e) {
length = ctb.nextByteIndex();
}
if (length < estLength) {
// A short format was used: Trim the byte array.
byte[] trimResult = new byte[length];
System.arraycopy(result, 0, trimResult, 0, length);
return trimResult;
}
else {
return result;
}
}