Use like this.
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Answer from Prince John Wesley on Stack OverflowUse like this.
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Try this
String[] arr = list.toArray(new String[list.size()]);
arrays - Converting 'ArrayList<String> to 'String[]' in Java - Stack Overflow
How can I convert my list<string> to a string[ ] array?
android - How to Convert arraylist<string> to string[] - Stack Overflow
Convert system.collection arrylist to string array
List<String> list = ..;
String[] array = list.toArray(new String[0]);
For example:
List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.
Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Java 11+:
String[] strings = list.toArray(String[]::new);
I am trying to write a simple code that will print out some names alphabetically but I wanna do it using a list.
I know that Array.Sort(); exists but I couldnt find a way to convert my list to an array.
using System; using System.Collections.Generic;
namespace siniflistesi { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("12-A sinif listesini gormek icin herhangi bir tusa basiniz."); Console.ReadKey(); Console.Clear();
List<string> yoklama = new List<string>(); string[] thearray = new string[yoklama.Count]; yoklama = Convert."i couldnt find an array option here" (thearray); Array.Sort(yoklama);
yoklama.Add ("Nehir"); yoklama.Add ("Zumra"); yoklama.Add ("Elif");
for (int i = 0; i < yoklama.Count; i++) { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine(yoklama[i]); } Console.ReadKey(); } } }