Blueaddiction Blueaddiction - 4 years ago 57
Java Question

How to use ArrayList to store multiple lines of information?

I created the following code:

int storagevar= arrayList.get(0);

for (int j=0; z<(storagevar-1); j++){
someString= normalArray[j];

This code looks through an
and gets the first element in there, which is a number representing an index in a second (normal)
s. It then uses this number to get the information from the second array, and stores it in another

This code is completely fine; it's the next bit thats causing a problem.

The above code assumes there is only 1 element inside the
. However, if there is more than one element, then I need to do the operation for each element in the
, so if there were 3 elements inside it, I would end up with the 3 indexes, and I would use them to extract the information from the normal
, and will end up with 3

I wrote the code below for the above scenario. I know it doesn't store each element answer in its own
, and I don't know how to do it; I need help with that too
. But anyways, this code doesn't seem to work either:

public void testMethod(){

MyClass test_one = arrayList.get(8);
String[] tmpStringArray = test_one.correct;
ArrayList<Integer> nnaCorrectAnswers = test_one.correctAnswers;

for (int i=0; i<nnaCorrectAnswers.size();i++){

tmp2= nnaCorrectAnswers.get(i);

for (int z=0; z<(tmp2 -1); z++){

Answer Source

If I understand correctly, you have an List<Integer> indices containing indices. For example, [2, 4, 6].

And you have an array strings containing Strings. For example: ["a", "b", "c", "d", "e", "f", "g", "h"].

And you want to create a list containing all the elements of the array whose indices are stored in the list. So, for example: ["c", "e", "g"] (because "c" is at index 2, "e" is at index 4, and "g" is at index 6).

Is that right? If so, all you need is:

List<String> result = new ArrayList<>();
for (int index : indices) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download