Java:打印所有arraylist元素

时间:2015-07-22 01:07:43

标签: java arraylist

如何使用for循环显示所有arraylist元素,我的代码如下所示:

ArrayList<String[]> theRecord = new ArrayList<String[]>(); 
PreparedStatement ps = conn.prepareStatement(strSQL);
ResultSet rs = ps.executeQuery();

int columnCount = rs.getMetaData().getColumnCount();

while(rs.next())
{
    String[] row = new String[columnCount];
    for (int i=0; i <columnCount ; i++)
    {
       row[i] = rs.getString(i + 1);
    }
    theRecord.add(row);
}

我想循环 theRecord 并按行和列获取所有元素。

2 个答案:

答案 0 :(得分:1)

Iterator<String[]> iter = theRecord.iterator();
while(iter.hasNext()){
   String[] temp = iter.next(); 
   for(int i=0;i<temp.length;i++){
       //manipulate temp[i]
   }
}

或其他例子:

import java.util.ArrayList;
import java.util.List;


public class ListString {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] str = new String[2];
        str[0] = "a";
        str[1] = "b";

        List<String[]> val = new ArrayList<String[]>();
        val.add(str);

        for(String[] s:val){
            for(int i=0;i<s.length;i++){
                System.out.println(s[i]);
            }
        }

    }

 }

后者的输出是
一个
B'/ P>

希望有所帮助。

答案 1 :(得分:0)

您可以使用ArrayList.get(int index)方法访问ArrayList的每个元素。

在这种情况下,您将使用它来迭代List的元素:

for(int i = 0; i < theRecord.size(); i++){
// Run over the elements in the List
for(int j = 0; j < theRecord.get(i).length(); j++)
// Run over the element itself. Through the indexes of the element Array.
// And do whatever you want with it
}
相关问题