I mostly familiar with Lua and just getting into Java. Below is the code I am trying to expand upon.
s1 = getResources().getStringArray(R.array.programming_languages);
What do I do if I want programming_langugages
to be determined by a variable?
testStr = "programming_languages";
How can I go about doing something similar to below, where testStr
is indexed? Below is similar to how I have done it in Lua, so I don't know what else to do, or even search for.
testStr = "programming_languages";
s1 = getResources().getStringArray(R.array[testStr]);
CodePudding user response:
In java arrays are represented by square brackets:
String [] programmingLanguages = ...
You can initialize in-place:
String [] programmingLanguages = {"C", "C ", "Java", "Lua"};
Or initialize by index:
String [] programmingLanguages = new String [4];
programmingLanguages[0] = "C";
programmingLanguages[1] = "C ";
programmingLanguages[2] = "Java";
programmingLanguages[3] = "Lua";
You can iterate over arrays, access by index and everything:
for(String language : programmingLanguages) {
System.out.println(language);
}
Or:
for(int index=0; index < programmingLanguages.length; i ) {
System.out.println(programmingLanguages[index]);
}
Note that you can't change the size of the array after the memory for it has been allocated, so programmingLanguage[5]="Pascal"
will throw an exception in runtime.
This might be too restrictive in a real life code challenges, so usually in Java people tend to use java.util.List
interface and its well-known implementation java.util.ArrayList
:
List<String> programmingLanguages = new ArrayList<>(); // note, no size specified in advance
programmingLanguages.add("C");
programmingLanguages.add("C ");
programmingLanguages.add("Java");
programmingLanguages.add("Lua");