I have a ArrayList which I add a Array to. How will I access the array from the ArrayList?
Example :
/*Storing the array*/
String[] Container = new String[3];
ArrayList arr =new ArrayList();
ResultSet rec1 = st.executeQuery ("SELECT * FROM HistoryHeader WHERE DocumentDate BETWEEN '"+startDate +"' AND '"+endDate+"'") ;
while(rec1.next ()) {
Container[0] = rec1.getString( "DocumentType") ;
Container[1] = rec1.getString( "DocumentNumber ");
Container[2] = rec1.getString( "CustomerCode") ;
arr.add(Contain er);
}
/*Viewing the String Array from the Array list*/
I want to access the array like arr.get(1)[1]
So get element 1 from the stored array from the first ArrayList element.
Whats the syntax for this?
You are on the right lines. However, the problem is that when you retrieve your String[] from your ArrayList using the .get(index) method, your String[] will be returned as an Object. If you are using an IDE like Eclipse or NetBeans it should tell you the type of the object that is being returned.
You have two options to solve this problem;
1. Cast the object being returned back to a String[].
So for example:
- String[] myArray = (String[])arr.get(1);
-
System.out.println(myArray[0]);
-
If you choose this approach, you should ensure that checks are made that the object being returned is actually a String[] before you get it, otherwise exceptions will be thrown when you recast the object. You can do this using the "instanceof " operator.
2. Make use of the ArrayList class' generics feature.
Many of the classes in the java.util package are "generic". This means that you can specify the type of object that they deal with. They will then provide type safety when you are adding and retrieving objects from the class. You can specify an ArrayList to contain String[]'s like so:
- ArrayList<String[]> myArrayList = new ArrayList<String[]>();
The type in between the < and > symbols specifies the type the ArrayList can handle. Once you have an instance of an ArrayList of this specification; your original code will work:
This is because the get(index) method now knows that it should return the type of String[] rather than Object.
Generics are very useful. You can read more about them
here .