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?
-
You'd need to recreate the array. Better use ArrayList or even better LinkedList.makasprzak– makasprzak2013-12-04 14:01:16 +00:00Commented Dec 4, 2013 at 14:01
-
I would rather use dynamic array for example List.Simon Dorociak– Simon Dorociak2013-12-04 14:01:57 +00:00Commented Dec 4, 2013 at 14:01
5 Answers
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.
Comments
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
1 Comment
List is an interface. You cannot instantiate it directly. =)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.
2 Comments
Vector is a good idea since it is kind of obsolete these days.