Как сделать массив массивов в Java
Гипотетически, у меня есть 5 строковых объектов массива:
String[] array1 = new String[];
String[] array2 = new String[];
String[] array3 = new String[];
String[] array4 = new String[];
String[] array5 = new String[];
и я хочу, чтобы другой объект массива содержал эти 5 строковых массивов. Как мне это сделать? Могу ли я поместить его в другой массив?
Ответы
Ответ 1
Вот так:
String[][] arrays = { array1, array2, array3, array4, array5 };
или
String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };
(Последний синтаксис может использоваться в назначениях, отличных от точки объявления переменной, тогда как более короткий синтаксис работает только с объявлениями.)
Ответ 2
попробовать
String[][] arrays = new String[5][];
Ответ 3
Пока есть два отличных ответа, рассказывающих вам, как это сделать, я чувствую, что другого ответа не хватает: в большинстве случаев вы не должны этого делать вообще.
Массивы громоздки, в большинстве случаев вам лучше использовать API коллекции.
С помощью коллекций вы можете добавлять и удалять элементы, а для разных функций есть специализированные подборки (поиск по индексу, сортировка, уникальность, FIFO-доступ, concurrency и т.д.).
Хотя, конечно, важно и важно знать о массивах и их использовании, в большинстве случаев использование Collections делает API более управляемым (поэтому новые библиотеки, такие как Google Guava вряд ли используют массивы).
Итак, для вашего сценария я бы предпочел список списков, и я бы создал его с помощью Guava:
List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));
Ответ 4
есть класс, о котором я упоминал в комментарии, который мы имели с Шон Патрик Флойд: я сделал это с особенным использованием, которое требует WeakReference, но вы можете легко сменить его любым объектом.
В надежде, что это когда-нибудь поможет кому-то:)
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
*
* @author leBenj
*/
public class Array2DWeakRefsBuffered<T>
{
private final WeakReference<T>[][] _array;
private final Queue<T> _buffer;
private final int _width;
private final int _height;
private final int _bufferSize;
@SuppressWarnings( "unchecked" )
public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
{
_width = w;
_height = h;
_bufferSize = bufferSize;
_array = new WeakReference[_width][_height];
_buffer = new LinkedList<T>();
}
/**
* Tests the existence of the encapsulated object
* /!\ This DOES NOT ensure that the object will be available on next call !
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
*/public boolean exists( int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
T elem = _array[x][y].get();
if( elem != null )
{
return true;
}
}
return false;
}
/**
* Gets the encapsulated object
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
* @throws NoSuchElementException
*/
public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
{
T retour = null;
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
retour = _array[x][y].get();
if( retour == null )
{
throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
}
}
else
{
throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
}
return retour;
}
/**
* Add/replace an object
* @param o
* @param x
* @param y
* @throws IndexOutOfBoundsException
*/
public void set( T o , int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
}
_array[x][y] = new WeakReference<T>( o );
// store local "visible" references : avoids deletion, works in FIFO mode
_buffer.add( o );
if(_buffer.size() > _bufferSize)
{
_buffer.poll();
}
}
}
Пример использования:
// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
if(myArray.exists(3,3))
{
System.out.println("Image at 3,3 is still in memory");
}