如何在Java中创建数组数组

如何在Java中创建数组数组,java,arrays,Java,Arrays,假设我有5个字符串数组对象: String[] array1 = new String[]; String[] array2 = new String[]; String[] array3 = new String[]; String[] array4 = new String[]; String[] array5 = new String[]; 我希望另一个数组对象包含这5个字符串数组对象。我该怎么做?我可以把它放到另一个数组中吗?试试看 String[][] arrays = new St

假设我有5个字符串数组对象:

String[] array1 = new String[];
String[] array2 = new String[];
String[] array3 = new String[];
String[] array4 = new String[];
String[] array5 = new String[];
我希望另一个数组对象包含这5个字符串数组对象。我该怎么做?我可以把它放到另一个数组中吗?

试试看

String[][] arrays = new String[5][];
像这样:

String[][] arrays = { array1, array2, array3, array4, array5 };


(后一种语法可用于变量声明以外的赋值,而较短的语法仅适用于声明。)

虽然有两个很好的答案告诉您如何做,但我觉得缺少另一个答案:在大多数情况下,您根本不应该做

数组很麻烦,在大多数情况下,最好使用

使用集合,您可以添加和删除元素,并且有用于不同功能(基于索引的查找、排序、唯一性、FIFO访问、并发性等)的专用集合

虽然了解数组及其用法当然是很好而且很重要的,但在大多数情况下,使用集合会使API更易于管理(这就是为什么像这样的新库几乎不使用数组的原因)

因此,对于您的场景,我更喜欢列表列表,并使用番石榴创建它:

List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));
List listofList=Lists.newArrayList();
添加(Lists.newArrayList(“abc”、“def”、“ghi”);
添加(Lists.newArrayList(“jkl”、“mno”、“pqr”);

我在与肖恩·帕特里克·弗洛伊德(Sean Patrick Floyd)的评论中提到了一个类:我使用了一个特殊的用法,需要WeakReference,但你可以通过任何对象轻松地更改它

希望有一天这能帮助某人:)

import java.lang.ref.WeakReference;
导入java.util.LinkedList;
导入java.util.NoSuchElementException;
导入java.util.Queue;
/**
*
*@作者leBenj
*/
公共类数组2DWeakRefsBuffered
{
私有最终WeakReference[][]\u数组;
专用最终队列缓冲区;
专用最终整数宽度;
私人最终内部高度;
专用最终整数缓冲区大小;
@抑制警告(“未选中”)
公共阵列2DWeakRefsBuffered(整数w、整数h、整数bufferSize)
{
_宽度=w;
_高度=h;
_缓冲大小=缓冲大小;
_数组=新WeakReference[_-width][_-height];
_buffer=newlinkedlist();
}
/**
*测试封装对象是否存在
*/!\n这不能确保对象在下次调用时可用!
*@param x
*@param y
*@返回
*@throws IndexOutOfBoundsException
*/公共布尔存在(int x,int y)引发IndexOutOfBoundsException
{
如果(x>=_宽度| | x<0)
{
抛出新的IndexOutOfBoundsException(“索引超出范围(get):[x=“+x+”]”);
}
如果(y>=|U高度| y<0)
{
抛出新的IndexOutOfBoundsException(“索引超出范围(get):[y=“+y+”]”);
}
如果(_数组[x][y]!=null)
{
T元素=_数组[x][y].get();
if(elem!=null)
{
返回true;
}
}
返回false;
}
/**
*获取封装的对象
*@param x
*@param y
*@返回
*@throws IndexOutOfBoundsException
*@NoSuchElementException
*/
公共T get(int x,int y)抛出IndexOutOfBoundsException,NoTouchElementException
{
T retour=null;
如果(x>=_宽度| | x<0)
{
抛出新的IndexOutOfBoundsException(“索引超出范围(get):[x=“+x+”]”);
}
如果(y>=|U高度| y<0)
{
抛出新的IndexOutOfBoundsException(“索引超出范围(get):[y=“+y+”]”);
}
如果(_数组[x][y]!=null)
{
retour=_数组[x][y].get();
if(retour==null)
{
抛出新的NoSuchElementException(“位于[“+x+”;“+y+”]”的解引用WeakReference元素);
}
}
其他的
{
抛出新的NoSuchElementException(“在[“+x+”;“+y+”]”处没有WeakReference元素);
}
回归回归;
}
/**
*添加/替换对象
*@param o
*@param x
*@param y
*@throws IndexOutOfBoundsException
*/
公共void集(to,int x,int y)抛出IndexOutOfBoundsException
{
如果(x>=_宽度| | x<0)
{
抛出新的IndexOutOfBoundsException(“索引超出范围(集合):[x=“+x+”]”);
}
如果(y>=|U高度| y<0)
{
抛出新的IndexOutOfBoundsException(“索引超出范围(集合):[y=“+y+”]”);
}
_数组[x][y]=新的WeakReference(o);
//存储本地“可见”引用:避免删除,在FIFO模式下工作
_添加(o);
如果(_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");
}
//一个5x5数组,最多有10个元素被“缓冲”->最后10个元素将不会被GC进程获取
Array2DWeakRefsBuffered myArray=新的Array2DWeakRefsBuffered(5,5,10);
图像img=myArray.set(anImage,0,0);
if(myArray.exists(3,3))
{
System.out.println(“3,3处的图像仍在内存中”);
}

Noob问题可能很严重。事实上,它们通常是::-)相关的问题和答案并不明显,因为谁知道内存对齐是如何完成的+1能否进一步解释第二种语法的作用?我有点不清楚。@特伦斯:它和第一个一样:它创建一个字符串数组引用数组,初始化为array1,array2,array3,array4和array5-它们本身都是字符串数组引用。快速问题:如果我不知道将创建多少数组对象,我将如何在运行时执行此操作?@Terence:您能给出一个更具体的示例吗?当您在编译时指定初始值时,您确实知道大小。你的意思是像
新字符串[10][]
这样的东西吗?是的。与彼得的答案相似
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");
}