user1872329
user1872329

Reputation: 361

Is there a way to delete object from Array in Java?

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

Answers (5)

An SO User
An SO User

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

maheeka
maheeka

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

Alberto Solano
Alberto Solano

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

Suresh Atta
Suresh Atta

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

Adam Arold
Adam Arold

Reputation: 30528

Use a List for this. You can remove and add to a List.

List<Player> players = new ArrayList<Player>();

Upvotes: 3

Related Questions