Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Another way to write this might be.</p> <pre><code>public class Start { private static final List&lt;String&gt; playerColours = Arrays.asList( "Red,Green,Blue,Yellow,Orange,Black,Purple".split(",")); private final List&lt;Player&gt; playerlist = new ArrayList&lt;Player&gt;(); public Start(int numberOfPlayers) { for(String playerColour: playerColors.subList(0, numberOfPlayers)) playerlist.add(new Player(playerColour)); } } </code></pre> <p>EDIT: To break this down.</p> <pre><code>private static final List&lt;String&gt; playerColours = Arrays.asList( "Red,Green,Blue,Yellow,Orange,Black,Purple".split(",")); </code></pre> <p>split(",") break a String into an array of String using the separator provided. So it is the same as.</p> <pre><code>private static final String[] playerColoursArray = {"Red", "Green", "Blue", "Yellow" ,"Orange", "Black", "Purple"} private static final List&lt;String&gt; playerColours = Arrays.asList(playerColoursArray); </code></pre> <p>Arrays.asList turns an array of Objects into a List.</p> <p>This line</p> <pre><code>for(String playerColour: playerColors.subList(0, numberOfPlayers)) </code></pre> <p>if the same as</p> <pre><code>List&lt;String&gt; subList = playerColors.subList(0, numberOfPlayers); for(String playerColour: subList) </code></pre> <p>the subList is view of the elements from <code>0</code> to <code>numberOfPlayers</code> So if <code>numberOfPlayers</code> is 3, you get a list of the first 3 colours. The <code>for</code> loop iterates of the elements in the subList so would iterate over the first 3 elements.</p> <p>The line</p> <pre><code>playerlist.add(new Player(playerColour)); </code></pre> <p>is similar to</p> <pre><code>Player player = new Player(); player.setName(playerColour); playerlist.add(player); </code></pre> <p>However it uses the constructor to construct the Player with the name. The advantage of using the constructor is that you can say a Player cannot be created without a name (with setters you cannot say that) You can also make the name <code>final</code> to make it clear it cannot change.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload