0

我从带有ORDER BY子句的 SQL 查询中加载 Java ArrayList 中的对象。

(1) 我可以使用foreach循环访问该 ArrayList 并按加载顺序将它们取回吗?

(2) 同样,我可以通过使用get(n)以相同的 SQL 顺序始终如一地获取元素吗?即,如果 SQL 行集中的第 3 个元素是“x”,get(2) 是否总是检索它?

4

3 回答 3

1

当然可以,这就是List的工作方式。你仍然可以使用http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html

于 2012-07-31T10:43:06.123 回答
1

Can I access that ArrayList with a foreach loop and get them back in the order in which they were loaded?

的,列表是有序集合。

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-31T10:43:48.183 回答
1

是的,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);
}

对于每个迭代器也保持相同的顺序。

于 2012-07-31T10:45:34.487 回答