2012-03-07 62 views
0

我的Java是生鏽的,我想知道,如果有人可以給我如何做下面的代碼示例:的java:格式設置到一個數組結果

我從數據庫中調用設置一個結果返回如下表:

OBJECT_ID

結果由OBJECT_ID這樣的分組,你有這樣的事情(INT),marker_id(INT),XPOS(浮動),ypos(浮動):
1023, 19, 0.2, 0.8
1023, 63, 0.2, 0.9
1023, 63, 0.2, 0.9
1072, 63, 0.2, 0.23
1072, 63, 0.2, 0.9
1072, 63, 0.2, 0.6
1012, 63, 0.2, 0.6
1012, 63, 0.2, 0.6

我一直在尋找用於產生兩個2D雙陣列,使得 第一個的最有效的方法具有 double[][] array1 = {
{0.2,0.8,0.2,0.9...},
{0.2,0.8,0.2,0.9...},
...}

每個子陣列含有序列X1,Y1,X2,Y2,X3,Y3爲ROW1,ROW2, etc ...爲結果集中相應的object_id。

第二個二維陣列將包含:
double[][] array2 = {
{1.0},
{0.9},
{0.8},
...
{0.0}}

哪裏有對於每個唯一的object_id中的條目和所述第一條目具有1.0和最後一個條目具有0.0

的兩個陣列應具有相同的長度因爲每個條目表示OBJECT_ID

希望是有道理的

感謝

回答

0

編輯回答以下

「我需要把它改造成陣列輸入到另一個庫。 - user257543「

那麼爲了做到這一點,一種方法是將列轉換爲一個數組,然後將它們組合起來,無論你想要什麼。

//get the size of the ResultSet 
    myResultSet.last(); 
    int resultSetSize = myResultSet.getRow(); 
    //initialize your arrays to be joined 
    int[] array1 = new int[resultSetSize]; 
    int[] array2 = new int[resultSetSize]; 
    //loop through the result so array1 will be the same as column1 of your table, etc. 
    int count = 0; 
    myResultSet.beforeFirst(); 
    while (myResultSet.next()){ 
     array1[count] = myResultSet.getInt("my column 1"); 
     array2[count] = myResultSet.getInt("my column 2"); 
     count++; 
    } 
    //declare rows and columns for easy code readability 
    int row = 0; 
    int column = 2; 
    //set your combined array row and column lengths 
    int[][] aCombined = new int[array1.length][column]; 
    //reset your column value to put array1 down column 0 
    column = 0; 
    for (int tempInt : array1){ 
     aCombined[row][column] = tempInt; 
     row++; 
    } 
    //reset your row and go to the next column to do the same as above 
    row = 0; 
    column = 1; 
    for (int tempInt : array2){ 
     aCombined[row][column] = tempInt; 
     row++; 
    } 

使用上述代碼,如果原始陣列是: INT []數組1 = {1,2,3,4}; int [] array2 = {5,6,7,8};然後 aCombined將導致[[1,5],[2,6],[3,7],[4,8]

哪位可以被可視化爲

  • [列1/ARRAY1,列2 /數組2]

  • [1,5]

  • [2,6]

  • [3,7]

  • [4,8]

原來的答案下面

爲什麼你需要把它改造成數組?爲什麼不直接使用結果集呢?

舉例來說,如果你需要得到所有的1072 OBJECT_ID對象的marker_id,只是:

public ArrayList getMarkerID(int objectId){ 
    ArrayList<int> myArrayList = new ArrayList<>(); 
    myResultSet.beforeFirst(); 
    while (myResultSet.next()){ 
     if (myResultSet.getInt("object_id") == objectId){ 
       myArrayList.add(myResultSet.getInt("marker_id")); 
     } 
     } 
     return myArrayList; 
    } 

(我剛纔輸入這件事真正的快,並沒有測試它,所以我可能會錯過一個分號或邏輯可能會關閉)

+0

我需要將其轉換爲數組,以便輸入到另一個庫。 – user257543 2012-03-07 21:15:09

+0

我編輯了上面的答案,它回答你的問題嗎? – TomJ 2012-03-08 16:23:07

+0

我喜歡數組方法,但我希望能夠檢測object_id的技術並將結果與​​此相關(如原始問題中所述)。儘管我認爲我可以通過調整您的方法來實現這一目標。謝謝! – user257543 2012-03-08 17:47:26