1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

気になったらすぐテストしよう

Posted at

少しでも不安があるときにはテストを書こう。
今は予想はできても、また困るかもしれない。

というわけで、予想はつくけど、多分動かして確認したことはないんじゃないかなぁ。
と思ったのでJavaのArrayListクラスのtoArrayメソッドをテストしてみる。
元のコードはJavaだけど、ここに掲載するのが面倒なのでGroovyです。

ArrayListToArrayCheck.groovy
// はたと困ったのでテスト
// T[] arr=ArrayList<T>.toArray(T[])
// で得られた配列arrをいじくるとどうなるんだったっけ?
// 予想では引数として与えた配列へ値がコピーされ、
// 返却値は配列への参照となっているハズ。
ArrayList<String> alist = new ArrayList<String>()
alist.add(0,'文字列1')
alist.add(0,'文字列2')
alist.add(0,'文字列3')
assert(alist.get(0)=='文字列3')
assert(alist.get(1)=='文字列2')
assert(alist.get(2)=='文字列1')
String[] strs = alist.toArray(new String[3])
String[] test = ['文字列3','文字列2','文字列1']
assert(strs == test)


// 配列の中身を変えてみる
strs[0] = strs[0].replace(/文字列/,'もじれつ')
strs[1] = strs[1].replace(/文字列/,'もじれつ')
strs[2] = strs[2].replace(/文字列/,'もじれつ')
assert(strs != test) // 配列の中身が変わった

String[] strs2 = alist.toArray(new String[3])
assert(alist.get(0)=='文字列3')
assert(alist.get(1)=='文字列2')
assert(alist.get(2)=='文字列1')
assert(strs != strs2) // alistの中身の変更はなし

// 引数にtestを与えてみる
test = ['文字列3','文字列2','文字列1']
strs = alist.toArray(test)
assert(strs[0]=='文字列3')
assert(strs[1]=='文字列2')
assert(strs[2]=='文字列1')
assert(strs == test)

// 配列の中身を変えてみる
strs[0] = strs[0].replace(/文字列/,'もじれつ')
strs[1] = strs[1].replace(/文字列/,'もじれつ')
strs[2] = strs[2].replace(/文字列/,'もじれつ')
assert(strs == test) // strsとtestが同時に変更されている。
println strs
println test
assert(strs.is(test)) // 参照が一致している。

予想通りでした。
書いた意味があったかどうかは、書いた人が決めればいいことです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?