I am trying to display all the String content from an arraylist, but the size of the arraylist is unknown (using Android Studio)
So for example:
fruit = new ArrayList<>()
veg = new ArrayList<>()
After some operations, now the story arraylist contained some information, such as:
fruit = {"apple", "orange", "banana", "peach",...};
veg = {"cucumber", "spinach", "pumpkin", "broccoli",...};
I do not know how long the arraylist of fruit and veg are after the operations. But I know that the fruit and veg has the same size of arraylist. I want to store each of the list to be like:
fruitOne = fruit(0), fruitTwo = fruit(1), fruitThree = fruit(2),...
vegOne = veg(0), vegTwo = veg(1), vegThree = veg(2),...
Then I want to display them together as a String? So that I can have a string such as:
String myStore = "I am selling" + fruitOne + " and " + vegOne + "/n" + fruitTwo + " and " + vegTwo + "/n" + fruitThree + " and " + vegThree"...;
I feel like it needs to use For loops to pull each of the list one by one by calling fruit(0), fruit(1),...,fruit(i)
. But how do I store each of this list of fruit(0), fruit(1),...,fruit(i)
independently, so that I can concatenate them together to become one String of myStore?
All the tutorial kept on taking about printLn or logd, so it can print the fruit(i) or veg(i) each for loop, but not really storing the fruit(i) or veg(i) as a variable to be used independently.
Thank you for your help!
2
Answers
There are multiple ways to turn a list of words into a full sentence.
One of which is what @deHaar mentioned.
Using
String.join( String , Iterable );
so in your case it would be something like this:You might aswell leave out the space chars in the list and add them only when joining them to form a sentence. So visually I mean like this:
I hope this answered your question.
New answer to updated question.
Based on what you are saying in comments:
I think you might have forgotten that the arrays of fruits and veggies are already variables you can use individually.
You can’t create more variables dynamically at runtime.
So for example turning an Array with 10 words cannot be turned into 10 individual variables at runtime.
etc… These have to be made at compile time (written declarations and assignments)
Unless you know the maximum size of your list you could create a bunch of variables and assign them like this:
I’d highly advise against doing this because hardcoding things like this really isn’t necessary. It is a huge amount of code with a hard limit.
It is also not possible to shuffle around variables within a loop you’re stuck with using a whole lot of if () {} else {} clauses. which would render the loop pointless.
The best way to get the values from the arrays is to get them directly from the Array instead of assigning each to a variable because you are limited to how many variables you create while an array list is dynamic in size.