How to get different elements of the same array for different objects of a class?

Welcome. There is an array of String[] which 32 elements(cards). There are class Players. You must write this method getCards, so when you call the Players p1.getCards, each of the players(p1,p2,p3,p4) was obtained on 8 different array elements, consecutive(p1 gets the first 8 elements, the following 8 p2). Causing an idea of how to organize the method getCards? Just getting started with java, and not sure what the best option would be to use an array. It is possible that nicer\more efficient use collection. Thank you!
October 3rd 19 at 03:07
4 answers
October 3rd 19 at 03:09
In the class Player to store the index (0, 1, 2, 3) player playerIdx.

Method getCards something like:

String[] getCards() {
 String[] ret = new String[8];

 int l = playerIdx * 8;
 int r = l + 8;
 for (int i = l, j = 0; i < r; i++, j++)
 ret[j] = cards[i]; 

 return ret;

If instead stringbag of the array is ArrayList, it will be possible in one line using the method subList().
And arrays in one line:

import java.util.Arrays;

String[] getCards() {
 return Arrays.copyOfRange(cards, playerIdx * 8, playerIdx * 8 + 8);
- pearl_Web commented on October 3rd 19 at 03:12
Oh, long enough to write in Java and only knew about the System.arraycopy() (although copyOfRange just a convenient wrapper over him, according to the source). I deliberately used to show the logic of the method. Thanks for copyOfRange :) - Hal68 commented on October 3rd 19 at 03:15
October 3rd 19 at 03:11
Obviously, you need to use the queue to a deck of cards, instead of an array.
I am not familiar with Java, so the specific classes/methods are not prompt.
October 3rd 19 at 03:13
I did not understand a bit, p1 is an instance of the Players class, according to his method .getCards() is not static, but at the same time, it performs the same action in any instance of this class (i.e. instance independent), and so it is logical to declare it static.

Let's say you have it static. Then it is logical to store a list of players (instances of the Players class) inside the class Players, to prevent an instance from it using new, making the constructor private and use to create instances of a static method getInstance(), at the address to which the list of players inside of the Players class to date.
Next you have your method Players.getCards(String[] cards), too static. There is no problem to run through the list of players in this class, and give everyone a piece of the array cards through the System.arrayCopy(). Can maps be stored in ArrayList and not in the array of while the concept of the program not visible to say that it is more appropriate.
October 3rd 19 at 03:15
Yes different can. Can be in a separate static class Game riveted the static SortCards, which will transmit instances of Players need the cards, but getCards then there will be no parameters.

Find more questions by tags Java