2015-01-14 4 views
0

알 수없는 레코드가 있고 문자열 2 차원 배열에 모든 레코드를 넣어야합니다.자바에서 동적 크기로 2 차원 문자열 배열을 초기화하십시오.

레코드 수를 알지 못하기 때문에 문자열 2 차원 배열 초기화에 필요한 행 및 열 수를 알지 못합니다. 여기

String[][] data = new String[100][100]; 

열심히 행과 열의 수를 구분하지만, 문자열 2 차원 배열에 뭔가 동적 크기의 허용이 필요합니다

현재 나는 다음과 같이 사용하고 있습니다. 어떤 제안 pls!

Rgrds

+0

출력? – Smutje

답변

5

HashMap에 데이터를 저장하고 2 차원 문자열 배열로 변환 할 수있는 다음 클래스를 사용할 수 있습니다.

public class ArrayStructure { 
    private HashMap<Point, String> map = new HashMap<Point, String>(); 
    private int maxRow = 0; 
    private int maxColumn = 0; 

    public ArrayStructure() { 
    } 

    public void add(int row, int column, String string) { 
     map.put(new Point(row, column), string); 
     maxRow = Math.max(row, maxRow); 
     maxColumn = Math.max(column, maxColumn); 
    } 

    public String[][] toArray() { 
     String[][] result = new String[maxRow + 1][maxColumn + 1]; 
     for (int row = 0; row <= maxRow; ++row) 
      for (int column = 0; column <= maxColumn; ++column) { 
       Point p = new Point(row, column); 
       result[row][column] = map.containsKey(p) ? map.get(p) : ""; 
      } 
     return result; 
    } 
} 

예제 코드

public static void main(String[] args) throws IOException { 
    ArrayStructure s = new ArrayStructure(); 
    s.add(0, 0, "1"); 
    s.add(1, 1, "4"); 

    String[][] data = s.toArray(); 
    for (int i = 0; i < data.length; ++i) { 
     for (int j = 0; j < data[i].length; ++j) 
      System.out.print(data[i][j] + " "); 
     System.out.println(); 
    } 
} 

당신은 자바 컬렉션 프레임 워크를 생각 해 봤나

1 
4 
+0

천재 답변에 감사드립니다! 이 접근 방식은 작동합니다! –

1

당신은 temporarely 그들은 List<String[]>에 저장하고 두 차원 배열로 변환 List#toArray(String[])를 사용할 수 있습니다.

public static void main(String[] args) throws IOException { 
    BufferedReader r = new BufferedReader(new FileReader(new File(
      "data.txt"))); 

    String line; 
    List<String[]> list = new ArrayList<String[]>(); 

    while ((line = r.readLine()) != null) 
     list.add(line.split(" +")); 

    String[][] data = new String[list.size()][]; 
    list.toArray(data); 

    for (int i = 0; i < data.length; ++i) { 
     for (int j = 0; j < data[i].length; ++j) 
      System.out.print(data[i][j]+" "); 
     System.out.println(); 
    } 
    r.close(); 
} 

데이터 .txt

1 2 3 4 5 
2 5 3 
2 5 5 8 

출력

1 2 3 4 5 
2 5 3 
2 5 5 8 
+0

감사 4 ur 답변! 하지만, i 번째 행과 n 번째 열과 같은 배열에 CSV 데이터를 저장하고 있습니다.이 값은 j 번째 행과 n + 12 번째 열에서 값이됩니다. like - str2dArr [i] [n] = "hi", str2dArr [j] [n + 12] = "hello". 이 경우 응답이 작동하지 않을 수 있습니다. 그렇지? 나는 List 을 사용하고 마침내 String [] []을 가져 오기위한 toArray를 사용할 수 있지만 여기에서는 반대편이 필요하다는 것을 알고있다. 어떠한 제안! 그 경우에는 –

+0

, 아니요 ... 2 차원 배열에 물건을 동적으로 추가 할 수 있어야하는 경우이 방법을 사용할 수 없습니다. –

+0

@SSingh이 문제를 해결하기위한 두 번째 대답을 확인하십시오. –

1

당신은 단순히 리터로 초기화 할 수 있습니다 iteral, 비어있는 2 차원 배열은 :

String[][] data = new String[][]{{}} 
+0

콘솔에서 예외가 발생했습니다 : "main"스레드의 예외 java.lang.ArrayIndexOutOfBoundsException : 1 데이터 배열에 데이터를 넣으려고하면! –

+0

동적 데이터와 해당 크기로 각 측정 기준을 초기화해야합니다. 그렇게하고 싶지 않다면 대신'Map >'을 사용해보십시오. 실제 동적 크기 조정을 사용할 수 있습니다. – Mena

0

이 작동합니다 :

public static void main(String args[]) throws IOException { 
    // create the object 
    String[][] data; 

    // ----- dinamically know the matrix dimension ----- // 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); 
    int r = Integer.parseInt(bufferedReader.readLine()); 
    int c = Integer.parseInt(bufferedReader.readLine()); 
    // ------------------------------------------------ // 

    // allocate the object 
    data = new String[r][c]; 

    // init the object 
    for (int i = 0; i < r; i++) 
     for (int j = 0; j < c; j++) 
      data[i][j] = "hello"; 
} 

당신이 매트릭스 차원 런타임을 알고이 예제에서는 콘솔을 통해 수동으로 지정.

관련 문제