如何用Java创建数组数组

Ter*_*nce 110 java arrays

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

String[] array1 = new String[];
String[] array2 = new String[];
String[] array3 = new String[];
String[] array4 = new String[];
String[] array5 = new String[];
Run Code Online (Sandbox Code Playgroud)

我希望另一个数组对象包含这5个字符串数组对象.我该怎么做?我可以把它放在另一个阵列中吗?

Jon*_*eet 141

像这样:

String[][] arrays = { array1, array2, array3, array4, array5 };
Run Code Online (Sandbox Code Playgroud)

要么

String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };
Run Code Online (Sandbox Code Playgroud)

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

  • @Terence:它与第一个相同:它创建一个字符串数组引用数组,初始化为值array1,array2,array3,array4和array5 - 每个引用本身都是一个字符串数组引用. (4认同)

Pet*_*rey 68

尝试

String[][] arrays = new String[5][];
Run Code Online (Sandbox Code Playgroud)

  • 如何将数据插入数组?如果是动态数据? (7认同)
  • @PrakharMohanSrivastava 您可以单独设置元素:`arrays[0] = new String[] {"a", "b", "c"}` 或使用临时列表:<pre><code> List<String[] > myList = new ArrayList<>(); myList.add(new String[]{"a", "b", "c"}); myList.add(new String[]{"d", "e", "f"}); myList.toArray(数组); </code></pre> (2认同)

Sea*_*oyd 24

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

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

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

虽然了解Arrays及其用法当然是好的和重要的,但在大多数情况下使用Collections使API更易于管理(这就是像Google Guava这样的新库根本不使用Arrays的原因).

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

List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));
Run Code Online (Sandbox Code Playgroud)


Ben*_*enj 5

在与肖恩·帕特里克·弗洛伊德(Sean Patrick Floyd)一起发表的评论中,我提到了一个类:我用的是特殊的用法,它需要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();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

使用方法示例:

// 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");
}
Run Code Online (Sandbox Code Playgroud)

  • +1是您的努力,但是:与其将int字段初始化为-1并在构造函数中重新分配它们,不如将它们定型,并在构造函数中“仅”分配它们。 (3认同)