多维数组列表java

时间:2014-03-11 17:48:57

标签: java android arraylist

我试图做一个多维ArrayList,所以我想出了这样做的方法:

int NumberInColumns = (int) Math.floor(listAnswers.size() / NUMBER_OF_COLUMNS);
// make higher number of answers on the right
if (listAnswers.size() % NUMBER_OF_COLUMNS > 0)
        NumberInColumns++;
ArrayList<HolderAnswer> listAnswers = getAnswers();
ArrayList<ArrayList<HolderAnswer>> listAnswersSorted = new ArrayList<ArrayList<HolderAnswer>>();

int k=0;
for (HolderAnswer answer : listAnswers) {
    ArrayList<HolderAnswer> temp = new ArrayList<HolderAnswer>();
    temp.add(answer);   
    if (k % NumberInColumns == 0 ) { 
            listAnswersSorted.add(temp);            
        }
        else { 
            if (k == listAnswers.size()) { 
                listAnswersSorted.add(temp);
            }
        }
        k++;
}

我遇到的问题是ArrayList.size()为7,我只是在尝试从阵列中获取信息时才获得第一和第五条记录。我错过了什么?

2 个答案:

答案 0 :(得分:0)

因此,实例化多维(我选择3D)arraylist可能如下所示:

List< List <List <Some Type Here>>> my3DList= 
new ArrayList< ArrayList < ArrayList <Some Type Here >() >() >();

首先让我们看一下如何从中获取数据......

ArrayList secondDemension = my3DList.get(0);
ArrayList thirdDemension = secondDemension.get(0);
SomeTypeHere value = thirdDemsion = 3D.List.get(0);

现在让我们看看如何迭代所有数据:

for(List<List<SomeType>> secondDemension in my3DList){
    for(List<sometype> thirdDemsion in secondDemension){
        for(YourType value in thridDemsion){
           System.out.println(value);
        }
    }

}

答案 1 :(得分:0)

Trying to sort an array to be displayed in table rows

ArrayList<HolderAnswer> listAnswers = getAnswers();
ArrayList<ArrayList<HolderAnswer>> listAnswersSorted =
new ArrayList<ArrayList<HolderAnswer>>();

// initialize the ArrayLists in listAnswersSorted
int numRows = listAnswers.size() / numColumns + 1;
for (int i = 0; i < numRows; i += 1) {
  listAnswersSorted.add(new ArrayList<HolderAnswer>());
}

// calculate column index where the "step" happens
int step = listAnswers.size() % numColumns;

// loop through and add elements to listAnswersSorted
int index = 0;
int row = 0;
int col = 0;
while (index < listAnswers.size()) {
  listAnswersSorted.get(row).add(listAnswers.get(index));

  int rows = col < step ? numRows : numRows - 1;
  row += 1;
  if (row == rows) {
    row = 0;
    col += 1;
  }
  index += 1;
}

// flatten the ArrayList<ArrayList> into a single ArrayList
ArrayList<HolderAnswer> newList = new ArrayList<HolderAnswer>();
for (ArrayList<HolderAnswer> list : listAnswersSorted) {
   newList.addAll(list);
 }