简体   繁体   中英

Remove an element from an ArrayList and move that element into an array java

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.

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()]);

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM