Java에서 배열 배열을 만드는 방법


115

가정적으로 5 개의 문자열 배열 객체가 있습니다.

String[] array1 = new String[];
String[] array2 = new String[];
String[] array3 = new String[];
String[] array4 = new String[];
String[] array5 = new String[];

다른 배열 개체에 5 개의 문자열 배열 개체를 포함하고 싶습니다. 어떻게하나요? 다른 배열에 넣을 수 있습니까?


43
멍청한 질문은 심각 할 수 있습니다. 사실, 그들은 자주 있습니다. :-)
TJ Crowder 2011 년

3
메모리 정렬이 수행되는 방법을 아는 사람에게는 적절한 질문과 대답이 명확하지 않습니다. +1
Benj 2011

답변:


153

이렇게 :

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

또는

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

(후자의 구문은 변수 선언 지점 이외의 할당에 사용할 수 있지만 더 짧은 구문은 선언에서만 작동합니다.)


두 번째 구문이 무엇을하는지 더 설명해 주시겠습니까? 제게는 불분명합니다.
Terence Ponce 2011 년

4
@Terence : 첫 번째와 동일합니다. array1, array2, array3, array4 및 array5 값으로 초기화 된 문자열 배열 참조 배열을 생성합니다. 각 배열은 그 자체로 문자열 배열 참조입니다.
Jon Skeet 2011 년

1
빠른 질문 : 얼마나 많은 배열 개체가 만들어 질지 모르는 경우 런타임에 어떻게해야합니까?
Terence Ponce 2011 년

1
@Terence : 좀 더 구체적인 예를 들어 주실 수 있나요? 당신이 컴파일시에 초기 값을 지정 할 때, 당신은 크기를 알고있다. 무슨 뜻 new String[10][]인가요?
Jon Skeet 2011 년

예. Peter의 대답과 비슷합니다.
Terence Ponce 2011 년

71

시험

String[][] arrays = new String[5][];

1
이것은 더
유연합니다

배열에 고정 크기를 정의해야하지 않습니까?
Filip

@Filip은 5로 고정되어 있습니다. 다음 레벨을 설정하면 미리 할당되지만 변경 될 수 있으므로 설정이 유용하지 않을 수 있습니다.
Peter Lawrey 2013-08-08

8
배열에 데이터를 어떻게 삽입합니까? 동적 데이터라면?
Prakhar Mohan Srivastava

1
@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>
kntx

26

방법을 알려주는 두 가지 훌륭한 답변이 있지만 다른 답변이 누락 된 것 같습니다. 대부분의 경우 전혀하지 말아야합니다.

배열은 번거 롭습니다. 대부분의 경우 Collection API를 사용하는 것이 좋습니다 .

컬렉션을 사용하면 요소를 추가 및 제거 할 수 있으며 다양한 기능 (인덱스 기반 조회, 정렬, 고유성, FIFO 액세스, 동시성 등)에 대한 특수 컬렉션이 있습니다.

물론 Array와 그 사용법에 대해 아는 것이 좋고 중요하지만 대부분의 경우 Collections를 사용하면 API를 훨씬 더 쉽게 관리 할 수 ​​있습니다 (이것이 Google Guava 와 같은 새로운 라이브러리가 Arrays를 거의 사용하지 않는 이유입니다 ).

따라서 귀하의 시나리오에서는 List of Lists를 선호하고 Guava를 사용하여 생성합니다.

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

String [] []보다 조금 더 복잡하지만 데이터 연결과 같은 더 많은 작업을 허용합니다. 그러나 솔루션이 데이터 크기를 보장하지 않아 문제가 될 수 있습니다.
Benj

1
@Benj 필요한 경우 특정 수의 항목 만 허용하는 List 데코레이터를 항상 작성할 수 있습니다.
Sean Patrick Floyd

정확한 데코레이터 / 래퍼는 일관성을 보장하는 좋은 방법입니다. 따라서 우리가 말하는 방식은 단순한 배열보다 훨씬 더 복잡합니다. 내가 한 것은 exixts (...) 등과 같은 몇 가지 기본 메서드를 캡슐화하는 작은 유틸리티 클래스 Array2D <T>입니다. 아래에 게시했습니다.
Benj

6

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();
        }
    }

}

사용 방법의 예 :

// 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");
}

4
노력에 +1하지만 : int 필드를 -1로 초기화하고 생성자에서 재 할당하는 대신 최종적으로 만들고 생성자 에서만 할당해야 합니다 .
Sean Patrick Floyd

1
@Sean : 코드를 수정했습니다 (현명한 의견을 포함하여 "no-GC 버퍼"로 새 코드를 게시했습니다.
Benj
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.