How to Remove string from array after randomly selecting it? Java -
i randomly selecting string array, , after selected create cannot take string again. should "delete" or there improve way?
here code randomly select it,
position = positionlist[(int) (math.random() * positionlist.length)];
deleting improve alternative if utilize arraylist
instead of array
. because in case of array, have either re-size (that means, have create new array everytime - deadly idea. avoid it), or set index selected null
.
but problem approach (setting null
) that, may have random selection many times 1 valid random index when left 1
valid index. so, it's improve utilize list
, , delete selected element it.
list<string> list = new arraylist<string>(); // populate list. collections.shuffle(list); // shuffle list. string random = list.remove(0); // remove first element
note that, if want original arraylist
, later one, can create re-create of it.
java arrays string random
No comments:
Post a Comment