簡體   English   中英

從有序的SQL將元素插入ArrayList

[英]Insert Elements to an ArrayList from ordered SQL

我正在從帶有ORDER BY子句的SQL查詢中加載Java ArrayList中的對象。

(1)我可以使用foreach循環訪問該ArrayList並按加載順序將其取回嗎?

(2)同樣,我可以通過使用get(n)一致地以相同的SQL順序獲取元素嗎? 即,如果SQL行集中的第三個元素是“ x”,則get(2)始終會檢索該元素嗎?

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

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)? Ie 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

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

每個迭代器也保持相同的順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM