How do I remove objects from an array in Java?

前端 未结 20 1680
Happy的楠姐
Happy的楠姐 2020-11-22 01:20

Given an array of n Objects, let\'s say it is an array of strings, and it has the following values:

foo[0] = \"a\";
foo[1]          


        
20条回答
  •  滥情空心
    2020-11-22 01:48

    I realise this is a very old post, but some of the answers here helped me out, so here's my tuppence' ha'penny's worth!

    I struggled getting this to work for quite a while before before twigging that the array that I'm writing back into needed to be resized, unless the changes made to the ArrayList leave the list size unchanged.

    If the ArrayList that you're modifying ends up with greater or fewer elements than it started with, the line List.toArray() will cause an exception, so you need something like List.toArray(new String[] {}) or List.toArray(new String[0]) in order to create an array with the new (correct) size.

    Sounds obvious now that I know it. Not so obvious to an Android/Java newbie who's getting to grips with new and unfamiliar code constructs and not obvious from some of the earlier posts here, so just wanted to make this point really clear for anybody else scratching their heads for hours like I was!

提交回复
热议问题