我使用ArrayList子句从ORDER 子句从查询中加载对象。
(1)我是否可以使用foreach循环访问该ArrayList,并按照加载它们的顺序让它们返回?
(2)类似地,我是否可以使用get(n)始终以相同的SQL顺序获得元素?也就是说,如果SQL行集中的第三个元素是"x",那么get(2)将总是检索它吗?
发布于 2012-07-31 10:43:48
Can I access that ArrayList with a foreach loop and get them back in the order in which they were loaded?
是,List的是有序集合。
Similarly, can I consistently get the elements in the same SQL order by using get(n)? I.e. if the 3rd element in the SQL rowset was "x", will get(2) always retrieve that?
是,正如我所说的,它们是有序的,按照插入的顺序,它们可以按照相同的顺序被检索。
List<String> ls=new ArrayList<String>();
ls.add("A");
ls.add("B");
ls.add("C");
for(String s:ls)
System.out.println(s);
System.out.println(ls.get(1));结果:
A
B
C
B发布于 2012-07-31 10:43:06
当然可以,这就是List的工作方式。您仍然可以使用http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html
发布于 2012-07-31 10:45:34
是的,Java中的ArrayList是有序集合。API说
List is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
当您从SQL加载到ArrayList时,您应该按照与SQL相同的顺序插入。代码片段应该是这样的
for (Each row starting from 0 in SQL) {
// add to arraylist using add method
list.add(sqlvalue);
}对于每个迭代器也保持相同的顺序。
https://stackoverflow.com/questions/11738245
复制相似问题