質問は、配列をリストに変換する方法について尋ねました。これまでのほとんどの回答は、配列と同じ内容の新しいリストを作成する方法、またはサードパーティのライブラリを参照する方法を示していました。ただし、この種の変換には簡単な組み込みオプションがあります。それらのいくつかは、他の回答ですでにスケッチされています(例:this one)。しかし、ここでは実装の自由度を指摘して詳しく説明し、潜在的な利点、欠点、および注意事項を示したいと思います。
少なくとも 2 つの重要な違いがあります。
- 結果のリストが配列のビューであるべきか、それとも新しいリストであるべきか
- 結果のリストを変更可能にするかどうか
ここでオプションを簡単に要約し、この回答の最後に完全なプログラム例を示します。
新しいリストの作成とアレイでのビューの作成
結果が新しいリストである必要がある場合は、他の回答からのアプローチのいずれかを使用できます。
List<Long> list = Arrays.stream(array).boxed().collect(Collectors.toList());
ただし、これを行うことの欠点を考慮する必要があります。1000000long
個の値を持つ配列は、約 8 メガバイトのメモリを占有します。新しいリストも約 8 メガバイトを占めます。そしてもちろん、このリストの作成中に配列全体をトラバースする必要があります。多くの場合、新しいリストを作成する必要はありません。代わりに、配列にビューを作成するだけで十分です。
// This occupies ca. 8 MB
long array[] = { /* 1 million elements */ }
// Properly implemented, this list will only occupy a few bytes,
// and the array does NOT have to be traversed, meaning that this
// operation has nearly ZERO memory- and processing overhead:
List<Long> list = asList(array);
(メソッドの実装については、下部の例を参照してくださいtoList
)
配列にビューがあるということは、配列の変更がリストに表示されるということです。
long array[] = { 12, 34, 56, 78 };
List<Long> list = asList(array);
System.out.println(list.get(1)); // This will print 34
// Modify the array contents:
array[1] = 12345;
System.out.println(list.get(1)); // This will now print 12345!
幸いなことに、ビューからコピー (つまり、配列の変更の影響を受けない新しいリスト) を作成するのは簡単です。
List<Long> copy = new ArrayList<Long>(asList(array));
さて、これは真のコピーであり、上に示したストリームベースのソリューションで達成されるものと同等です。
変更可能なビューまたは変更不可能なビューの作成
多くの場合、リストがread-onlyであれば十分です。多くの場合、結果のリストの内容は変更されませんが、リストを読み取るだけの下流の処理に渡されるだけです。
リストの変更を許可すると、いくつかの疑問が生じます。
long array[] = { 12, 34, 56, 78 };
List<Long> list = asList(array);
list.set(2, 34567); // Should this be possible?
System.out.println(array[2]); // Should this print 34567?
list.set(3, null); // What should happen here?
list.add(99999); // Should this be possible?
変更可能な配列にリスト ビューを作成することができます。これは、特定のインデックスに新しい値を設定するなど、リストの変更が配列に表示されることを意味します。
ただし、構造的に変更可能なリスト ビューを作成することはできません。これは、リストのサイズに影響を与える操作を行うことができないことを意味します。これは、基になる配列のサイズを変更できないためです。
以下は、さまざまな実装オプションと、結果のリストを使用する可能な方法を示すMCVEです。
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.RandomAccess;
public class PrimitiveArraysAsLists
{
public static void main(String[] args)
{
long array[] = { 12, 34, 56, 78 };
// Create VIEWS on the given array
List<Long> list = asList(array);
List<Long> unmodifiableList = asUnmodifiableList(array);
// If a NEW list is desired (and not a VIEW on the array), this
// can be created as well:
List<Long> copy = new ArrayList<Long>(asList(array));
System.out.println("array : " + Arrays.toString(array));
System.out.println("list : " + list);
System.out.println("unmodifiableList: " + unmodifiableList);
System.out.println("copy : " + copy);
// Modify a value in the array. The changes will be visible
// in the list and the unmodifiable list, but not in
// the copy.
System.out.println("Changing value at index 1 of the array...");
array[1] = 34567;
System.out.println("array : " + Arrays.toString(array));
System.out.println("list : " + list);
System.out.println("unmodifiableList: " + unmodifiableList);
System.out.println("copy : " + copy);
// Modify a value of the list. The changes will be visible
// in the array and the unmodifiable list, but not in
// the copy.
System.out.println("Changing value at index 2 of the list...");
list.set(2, 56789L);
System.out.println("array : " + Arrays.toString(array));
System.out.println("list : " + list);
System.out.println("unmodifiableList: " + unmodifiableList);
System.out.println("copy : " + copy);
// Certain operations are not supported:
try
{
// Throws an UnsupportedOperationException: This list is
// unmodifiable, because the "set" method is not implemented
unmodifiableList.set(2, 23456L);
}
catch (UnsupportedOperationException e)
{
System.out.println("Expected: " + e);
}
try
{
// Throws an UnsupportedOperationException: The size of the
// backing array cannot be changed
list.add(90L);
}
catch (UnsupportedOperationException e)
{
System.out.println("Expected: " + e);
}
try
{
// Throws a NullPointerException: The value 'null' cannot be
// converted to a primitive 'long' value for the underlying array
list.set(2, null);
}
catch (NullPointerException e)
{
System.out.println("Expected: " + e);
}
}
/**
* Returns an unmodifiable view on the given array, as a list.
* Changes in the given array will be visible in the returned
* list.
*
* @param array The array
* @return The list view
*/
private static List<Long> asUnmodifiableList(long array[])
{
Objects.requireNonNull(array);
class ResultList extends AbstractList<Long> implements RandomAccess
{
@Override
public Long get(int index)
{
return array[index];
}
@Override
public int size()
{
return array.length;
}
};
return new ResultList();
}
/**
* Returns a view on the given array, as a list. Changes in the given
* array will be visible in the returned list, and vice versa. The
* list does not allow for <i>structural modifications</i>, meaning
* that it is not possible to change the size of the list.
*
* @param array The array
* @return The list view
*/
private static List<Long> asList(long array[])
{
Objects.requireNonNull(array);
class ResultList extends AbstractList<Long> implements RandomAccess
{
@Override
public Long get(int index)
{
return array[index];
}
@Override
public Long set(int index, Long element)
{
long old = array[index];
array[index] = element;
return old;
}
@Override
public int size()
{
return array.length;
}
};
return new ResultList();
}
}
この例の出力を次に示します。
array : [12, 34, 56, 78]
list : [12, 34, 56, 78]
unmodifiableList: [12, 34, 56, 78]
copy : [12, 34, 56, 78]
Changing value at index 1 of the array...
array : [12, 34567, 56, 78]
list : [12, 34567, 56, 78]
unmodifiableList: [12, 34567, 56, 78]
copy : [12, 34, 56, 78]
Changing value at index 2 of the list...
array : [12, 34567, 56789, 78]
list : [12, 34567, 56789, 78]
unmodifiableList: [12, 34567, 56789, 78]
copy : [12, 34, 56, 78]
Expected: java.lang.UnsupportedOperationException
Expected: java.lang.UnsupportedOperationException
Expected: java.lang.NullPointerException