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;
}
5
  • 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. Commented Jan 23, 2019 at 9:40
  • 2
    Why don't use String[] arrayForTheList = (String[]) stringList.toArray();? Commented Jan 23, 2019 at 9:41
  • Why don't you try something like: String[] array = new String[stringList.size()]; return stringList.toArray(array); Commented Jan 23, 2019 at 9:41
  • You can use remove, becuse it decrements the size of the list that you use dynamically in the loop Commented Jan 23, 2019 at 9:44
  • 1
    I originally marked as a duplicate of stackoverflow.com/questions/7969023/from-arraylist-to-array. Not quite the same, but the linked SO question offers a better conversion mechanism Commented Jan 23, 2019 at 9:45

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Yeah, the problem is stringList.size() changes every iteration, because of stringList.remove(0).
1

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

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

Hope this helps.

2 Comments

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]);
Yes you are correct, I forgot to cast to String[]. I updated my answer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.