1

I can't figure out why the last value of stringList (ie, Banana) is not being printed out or stored in arrayForTheList for that matter.

Given a list of Strings, return an array containing the same Strings in the same order

list2Array( ["Apple", "Orange", "Banana"] )         ->  {"Apple", "Orange", "Banana"}
list2Array( ["Red", "Orange", "Yellow"] )           ->  {"Red", "Orange", "Yellow"}
list2Array( ["Left", "Right", "Forward", "Back"] )  ->  {"Left", "Right", "Forward", "Back"}

public String[] list2Array(List<String> stringList) {

    String[] arrayForTheList = new String[(stringList.size())];

    for (int i = 0; i < stringList.size() ; i++) {
        arrayForTheList[i] = stringList.remove(0);
        System.out.println(arrayForTheList[i]); 
    }

    return arrayForTheList;
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • 2
    You're incrementing `i` _and_ you're deleting from the start of the list, so the elements are being moved towards the start of the list. – khelwood Jan 23 '19 at 09:40
  • 2
    Why don't use `String[] arrayForTheList = (String[]) stringList.toArray();`? – Dang Nguyen Jan 23 '19 at 09:41
  • Why don't you try something like: String[] array = new String[stringList.size()]; return stringList.toArray(array); – Stultuske Jan 23 '19 at 09:41
  • You can use remove, becuse it decrements the size of the list that you use dynamically in the loop – azro Jan 23 '19 at 09:44
  • 1
    I originally marked as a duplicate of https://stackoverflow.com/questions/7969023/from-arraylist-to-array. Not *quite* the same, but the linked SO question offers a better conversion mechanism – Brian Agnew Jan 23 '19 at 09:45

3 Answers3

1

You shouldn't remove elements from the List inside your loop. You can clear the List after the loop if you have to.

for (int i = 0; i < stringList.size() ; i++) {
    arrayForTheList[i] = stringList.get(i);
    System.out.println(arrayForTheList[i]); 
}
stringList.clear();
Eran
  • 387,369
  • 54
  • 702
  • 768
1

You can simply implement this by using the toArray() method of lists. For example:

String[] arrayForTheList = (String[])stringList.toArray();

Hope this helps.

Ben
  • 66
  • 5
  • 1
    uhmm, you may forget to cast to String[] `Type mismatch: cannot convert from Object[] to String[]`, or a better way is `String[] arrayForTheList = stringList.toArray(new String[0]);` – Dang Nguyen Jan 23 '19 at 09:55
  • Yes you are correct, I forgot to cast to String[]. I updated my answer. Thanks! – Ben Jan 23 '19 at 09:57
1

Replace

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

to

for (int i = 0; i < arrayForTheList.length ; i++)

Keep in mind that your code clear List which it receive as parameter.

talex
  • 17,973
  • 3
  • 29
  • 66
  • Yeah, the problem is `stringList.size()` changes every iteration, because of `stringList.remove(0)`. – Jeppe Jan 23 '19 at 09:48