Java for everyone with a getter

Some time has passed since the last time I used Java, since I am primarily a C # developer. To get back into the game, I worked on a very simple application to cover most of the key language features. I ran into the following problem:

for (Player player : teamRed.getPlayers()) {
    System.out.format("> %s\n", player.getName());
}

Where is getPlayers()defined as follows:

public Iterable<Player> getPlayers() {
    return Collections.unmodifiableList(this.players);
}

At some point in the past, either C # or Java had performance problems when you used getter in yours for everyone, like this, since it would execute the method on each iteration. There is nothing I can do about it anymore, so I wonder:

Was Java subject to this problem, or was it only for C #?

, , getPlayers . , : P

+4
1

( iterator() Iterable), , getPlayers() . , getPlayers()

public Iterable<Player> getPlayers() {
    System.out.println("getPlayers() called");
    return Collections.unmodifiableList(this.players);
}

"getPlayers(), " .

Iterable ( iterator()): https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html

+3

Source: https://habr.com/ru/post/1652497/


All Articles