1

I'm writing a method that removes an element from an ArrayList of strings, if it is of a given length, and puts the removed String into an Array containing Strings, and I'm a bit confused at how to insert elements into the array after removing them from the List.

My ArrayList is called list, and it's an instance variable in the beginning of my program.

public String[] removeOfLength(String [] arr, int wordLength)
{
    arr = new String[list.size()];
    for(int i = 0; i < list.size(); i++)
    {
        if(list.get(i).length == wordLength)
        {
            list.remove(i);
            //arr[i]
        }
    }
} 

I removed the element, but I don't know how to insert it into the array. The method is supposed to return a String array containing the removed Strings.

1
  • Ideally, you should either accept the String[] or return it. Returning it with explicit assignment is preferred as it makes the intent of your code clear. At just first glance, it's difficult to see that an array I'm passing to a method would be wiped clean. Commented Jan 21, 2015 at 4:35

3 Answers 3

3

Instead of creating an array first, which has to be as long as the list itself, use a list again to hold the removed strings temporarily.

List<String> removedStrings = new ArrayList<String>();
for(int i = 0; i < list.size(); i++)
{
    if(list.get(i).length == wordLength)
    {
        removedStrings.add(list.remove(i));
    }
}

Then just convert the list into an array when the method ends

return removedStrings.toArray(new String[removeStrings.size()]);
Sign up to request clarification or add additional context in comments.

Comments

0

Just assign the value at a certain index. Also the remove method returns the value removed from the list. arr[I]=list.remove(I);

Also you need to return arr at the end of the method. And if the method calling this one expects the array that its providing as an argument to have the elements it won't because you are assigning it a new reference at the beginning. Also, the array will not fill like a list, there will be gaps if it doesn't remove every element from your list, arrays aren't smart like ArrayLists.

Comments

0

Since array is a fixed length structure and you have to specify the length at the creation, you cannot directly insert removed element to a new array because you don't know how many elements will be there in array.

Instead, you can use the arraylist to keep removed elements temporarily and at the end of the iteration, populate those to a new array (because at that point, you know the length of the array using number of elements in your temporary arraylist).

Comments

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.