Reputation: 361
I'm working on a board game. I have an array of objects Player[] player, let's say player[0], player[1], player[2]. If player[1] finishes a game first, other players continue to play. I need cycle for to skip this player's index. Is there a way to do so?
Upvotes: 1
Views: 402
Reputation: 24998
You can use a dynamic 'array' like ArrayList
.
List<String> list = new ArrayList<String>();
list.add("John");
list.add("Doe");
list.add("Foo Bar");
System.out.println(list.size()); // Expands
list.remove(0);
System.out.println(list.size()); // Shrinks
You can run the example here and see the output: http://ideone.com/ciDSwa
So, in your context, you can do as follows:
List<Player> players = new ArrayList<Player>();
// add players
// remove players
The term 'expands' and 'shrinks' should be taken with a grain of salt because it only expands if the number of objects goes beyond a certain threshold. After that, the contents of the ArrayList
are copied to a new location in the memory.
Upvotes: 0
Reputation: 2093
To allow such removing of items, its best to use Lists which will allow both add and remove conveniently. In arrays, you cannot remove an item, but you could set the value to null and check if the value is null when iterating.
Upvotes: 0
Reputation: 8227
An array is not a dynamic data structure, where you can add or remove an item in an easy way.
You should use a collection, like a List
or an ArrayList
or even a LinkedList
, for example. The list data structures are much easier to use and mantain, because they've methods that let you add/remove or find your items.
For example, in a List, you can add a new item or remove an existing one, in this way:
List<MyType> myList = new ArrayList<MyType>(); //creation of List
MyType myObject = new MyType(); //creation of the object you want to add to the list
myList.add(myObject); //to add your item
myList.remove(myObject); //to remove your item
Upvotes: 2
Reputation: 121998
No, you cannot remove from an array. Maximum you can do is making that is null
player[1]= null;
Your best bet is to go for a List Interface
.
P.s Arrays
usage was limited after the introduction of Collections.
Upvotes: 3
Reputation: 30528
Use a List
for this. You can remove
and add
to a List
.
List<Player> players = new ArrayList<Player>();
Upvotes: 3