How do I randomly select a string from an array in swift?

How do you split a string[] array to separate strings in java?

  • Basically I have a string array: String[] menuItems = { "Item 1", "Item 2", "Item 3" }; and i want to convert it to separate strings like: String item1 = "Item 1" String item2 = "Item 2" String item3 = "Item 3" Then I want to take all three elements plus a newly created element: String item4 = "Item 4" and put them all back into the original string array. To put it in context, I have created an activity in android that extends the ListActivity which is used to create a simple menu. The ListAdapter uses an Array adapter to assign each menu option name. So really, i just need to add one more element to the String[] Array so that another menu option will appear. How do I make: String[] menuItems = { "Item 1", "Item 2", "Item 3" }; turn into String[] menuItems = { "Item 1", "Item 2", "Item 3", "Item 4" }; Thanks for the help!

  • Answer:

    Arrays in Java have a fixed size; to do something like this you would need to either create the array with 4 elements to start, or make an entirely new array and copy all four elements into it. This is why arrays are not the right thing to use for something like this. Use a proper Collection class, like ArrayList, instead.

Silent at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

You'll need to create a new array separate from menuItems in order to store item4 because the length of an array is a final member meaning that it cannot be changed once instantiated (arrays in java are immutable in size but mutable in that its elements can be modified). A better way to approach this would be to use an ArrayList (java.util.ArrayList) and use the .add(E element) method to add new items. This is one way to go about it with arrays: String[] menuTwo = new String[menuItems.length+1]; for(int i=0;i<menuItems.length;i++){ menuTwo[i]=menuItems[i]; } menuTwo[menuTwo.length] = item4; menuItems=menu2; For an ArrayList: ArrayList<String> menuItems = ArrayList<String>(); //assuming menuItems already contains item1, 2, and 3 String item4 = "Item 4"; menuItems.add(item4); //You can also simply do menuItems.add(new String("Item 4"));

Tsurupettan

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.