Hi,
Ewald gived you a very good advice:
alocate every time a new array. And emphasized the point that ArrayList
objects (and all collection classes) are storing references. When you create
a new array, a new reference is created every time, so they aren't repeated.
*I think Ewald suggested the best practice*.
You give here a very simple example but in practice is usually need of a
function. Probably in practice you will need a function like this
private static void addElement(String a1, String a2, String a3, String a4)
{
String[] strArray={a1,a2,a3,a4};
arlQueryResult.add(strArray);
}
This way you also get rid of 4 lines in program
strQueryResult[0] = "a";
strQueryResult[1] = "b";
strQueryResult[2] = "c";
strQueryResult[3] = "d";
For this kind of code I have a simple rule (as many programming books
suggested and I rediscovered it myself few years ago):
If you have to run a piece of code you need only once, write it.
If you have to run a piece of code many times, use fuctions. Many times you
can reuse the functions and this speeds your work.
Considering you have a program which gives you 4 strings, the function above
make sense.
You can also make a "shallow copy" which also creates a new reference. If
you don't want to create a new array you can create a clone (but this way
you would spend time to create a copy of the array).
See function addElement below. The "clone" function is in class Object which
in Java is the root of all classes.
See here the java documentation here.
http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html
import java.util.ArrayList;
public class TestArrayList1 {
static ArrayList<String[]> arlQueryResult = new
ArrayList<String[]>(10);
static String[] strQueryResult = new String[4];
public static void main(String[] args) {
strQueryResult[0] = "a";
strQueryResult[1] = "b";
strQueryResult[2] = "c";
strQueryResult[3] = "d";
addElement(strQueryResult);
strQueryResult[0] = "e";
strQueryResult[1] = "f";
strQueryResult[2] = "g";
strQueryResult[3] = "h";
addElement(strQueryResult);
for (int i = 0; i< arlQueryResult.size(); i++){
for (int j = 0; j<=3; j++){
String str = arlQueryResult.get(i)[j];
System.out.println("Result " + i + j + ": " +
str);
}
}
}
/**
* add a string element to an ArrayList<String[]>
* @param element
*/
private static void addElement(String[] element)
{
*arlQueryResult.add((String[])element.clone());
* }
}
Best regards,
Vasile Braileanu
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---