0

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?

3
  • Yes, If you add the elements in the order from the SQL query. Show your code please. Commented Jul 31, 2012 at 10:40
  • unless you perform sort like operations on arraylist . Commented Jul 31, 2012 at 10:41
  • 1
    Usually yes, but it depends on how you load elements from DB to ArrayList. As juergen d said, show some code. Commented Jul 31, 2012 at 10:41

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.