java - How can I set specific item in an ArrayList, without getting the OutOfBounds error? -


i trying code trade plugin game. idea player sends request player, , if other player accepts, each side has choose item trade.

i have 4 arraylists: store requesters, store requested, store requester's chosen item , store requested's chosen item. problem if multiple players trade @ same time, can't add item list, because can match else's trade. tried this:

requesteritems.set(requesterindex, clicked); 

where requesterindex index of requester in other list , clicked item that's selected.

i know why there error, can't think of workaround. problem list empty , there no element @ index. how can add element there without touching other spots in list?

i avoid work concrete indexes if possible , work objects instead.

as mentioned in comments, recommend own class hashmap. heres bit of code (!not tested!):

private hashmap<yourplayerclass, list<youritemclass>> playeritemmap = new hashmap<>();  private void tradeitems(yourplayerclass p_player1, yourplayerclass p_player2,                         youritemclass p_itemofplayer1, youritemclass p_itemofplayer2) {      list<youritemclass> itemsofplayer1 = playeritemmap.get(p_player1);      list<youritemclass> itemsofplayer2 = playeritemmap.get(p_player2);       //carry out trade player 1      itemsofplayer1.remove(p_itemofplayer1);      itemsofplayer1.add(p_itemofplayer2);      playeritemmap.put(p_player1, itemsofplayer1); //not sure if put necessary       //carry out trade player 2      itemsofplayer2.remove(p_itemofplayer2);      itemsofplayer2.add(p_itemofplayer1);      playeritemmap.put(p_player2, itemsofplayer2); //not sure if put necessary } 

so theres hashmap player key , his/her items list-value.

the code example isn't failure safe. recommend add check if items in list avoid errors. like:

if(itemsofplayer1.contains(p_itemofplayer1)) {     //carry out trade } else     system.err.println("player 1 tried trade item wasn't in his/her inventory! shouldn't possible!"); 

i hope helps bit solve problem, let me know if i've got wrong! luck!


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -