Reputation: 4827
I am loading objects in an Java ArrayList from a SQL Query with an ORDER BY clause.
(1) Can I access that ArrayList with a foreach loop and get them back in the order in which they were loaded?
(2) 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?
Upvotes: 0
Views: 457
Reputation: 1212
Yes ArrayList in Java is Ordered Collection. API says
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.
When you load from SQL to ArrayList you should exactly insert in the same order as of SQL. code snippet should be like this
for (Each row starting from 0 in SQL) {
// add to arraylist using add method
list.add(sqlvalue);
}
for each iterator also maintain the same order.
Upvotes: 1
Reputation: 7899
Can I access that ArrayList with a foreach loop and get them back in the order in which they were loaded?
Yes, List's are ordered collection .
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?
Yes , As i said they are ordered , in the order they are inserted they can be retrieved in the same order.
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));
Results:
A
B
C
B
Upvotes: 1
Reputation: 3170
sure you can, this is how List works. still you can use http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html
Upvotes: 1