This has been confusing me for a while, picture this
public class someObject {
private ArrayList<Player> listOfPlayers = new ArrayList<Player>();
private String name;
public void addPlayer(Player player){
listOfPlayers.add(player);
}
}
Multiple instances of this object can be created during the game, what i don't understand is how do you update the ArrayList of a specific instance, for example
There are 10 instances currently of the someObject class Player 1, 2 and so on. Player 5 wants to add a player to his listOfPlayers, how would i handle getting the arraylist of his specific instance where he is currently in the listOfPlayers.
What i have been doing is
for (int i = 0; i < objects.size(); i ++){ //ArrayList<someObject>
someObject temp = someObject.get(i);
if (temp.listOfPlayers.contains(player)){
return true;
}
}
Which works but it seems so wrong using for loops in every getter and setter of the someObjects class, is there a better way than this ?
A better solution/alternative would be using a Map.
Map<someObject, List<Players>> objPlayersMap= new HashMap.....
Later, you can check your condition just like
objPlaersMap.get(someObject).contains(...
If you want, u can modify your "Player" class and add an id. With setter and getter u can handle these with this id. Its an idea, if u wanna prefer it more.
The best way is to use a map with the name of the player as a key. In that way you can get the list easily without a loop
Map<String, List<Players>> players = new HashMap<String,List<Players>>();
players.put("player1", new SomeObject());
players.put("player2", new SomeObject());
....
after that you do that:
List<Players> player1 = players.get("player1");
Related
I realize that variations of this question have been asked before, but I am having a uniquely difficult time figuring out how to complete the following task:
I have an object that looks something like this (please note, "Skill" and "Certification" are ENUMS):
Public Employee {
String name;
List<Skill> employableSkills = new ArrayList<>();
List<Certification> certifications = new ArrayList<>();
...
}
In another class, I've got a
List<Employee> listOfEmployees;
and I'm trying to loop through it like this:
// determine the total number of employees who know Java
int numberOfEmployeesWhoKnowJava = 0;
for (Employee employee : listOfEmployees) {
if (employee.employableSkills.contains( ?? )) {
numberOfEmployeesWhoKnowJava++;
}
I'm struggling to get the exact syntax on the if-statement. I have tried this:
if(employee.employableSkills.contains(Employee.EmployableSkills.JAVA)) {
but EmployableSkills in this string gets "cannot resolve symbol."
How should I loop through the List on each Employee object and check if it contains JAVA?
Edit: It turns out I was making a fundamental error. In OOP, it is best not to expose the data from one class to another class. Instead, I wrote getters in the Employee class, then called those getters from my other class. That way, the data in Employee is not directly exposed to the class that needed it.
Even if you get syntax right, the following code will have a bad complexity of order n - O(n).
if(employee.employableSkills.contains(Employee.EmployableSkills.JAVA)) {
Change you List to hash implementation of set
Set<Skill> employableSkills = new HashSet<>();
and now loop through the employees
int numberOfEmployeesWhoKnowJava = 0;
for (Employee employee : listOfEmployees) {
if (employee.employableSkills.contains(Skill.JAVA)) {
numberOfEmployeesWhoKnowJava++;
}
}
This will give a complexity of O(1) while looking skills
Your question is a little unclear, but if my interpretation is correct, try this:
if (employee.employableSkills.contains(Skill.JAVA))
I have two objects that are being stored in arrays:
Game(String creator, String title, int releaseYear, int NumberSold)
Creator(String name, String gamesWorkedOn)
Game(creator) has multiple creators, so is stored as a string like this: "creator1, creator2, creator3" using commas to separate their values.
Not all games have multiple creators and there are not many different creators in total.
What I am trying to do is loop through an array of Game(games) and extract a creator variable from it and assign it to the Creator(name) and then match any games that creator is mentioned in and assign those title variables to Creator(gamesWorkedOn).
So far I have this:
public static void PopulateCreators(ArrayList<Game> games) {
//populating an array of Creators with games they have worked on
boolean match = false;
String thisCreator;
String gamesWorkedOn;
ArrayList<Creator> creatorArray = new ArrayList<Creator>();
for (int i = 0; i < games.size(); i++) {
thisCreator = games.get(i).getGameCreator();
thisCreator = thisCreator.replaceAll(", ", "\n");
Which gives me this output using a sysout:
Shigeru Miyamoto
Satoshi Tajiri
Yoshiaki Koizumi
Koichi Hayashida
Shigeru Miyamoto
My desired output would be to have something like this:
name = "Shigeru Miyamoto"
gamesWorkedOn = "game1, game2, game3"
I am looking at using a for loop but am unsure on how to implement it here.
Edit:
I forgot to mention a couple of details that I didn't think were important but I will be a bit clearer now. This is a Swing based project I am working on that takes user inputs and stores these arrays which are then saved into a JSON file that is read upon loading of the application and when a user clicks a 'save' button.
What you seem to want to do is map the creators to all the games that they have created or helped create. I'm going to start by creating a simplified version of the problem.
You have a list of:
class Game {
Set<Creator> creators;
}
which you want to convert to:
Map<Creator, Set<Game>> createdGames; // Map of creator name to games created
The first thing to do here is to find all of the unique creators to start adding to the map. This can be done with the stream API.
createdGames = gameList.stream().flatMap(game -> game.creators.stream()).distinct().collect(Collectors.toMap(Function.identity(), v -> new HashSet<>()));
Now you can just loop through all the games again and add the game to a creator's set if they took part in the creation of that game.
for(Game game : gameList) {
for(Creator creator : createdGames.keySet()) {
if(game.creators.contains(creator)) {
createdGames.get(creator).add(game);
}
}
}
I would like to ask if there is a way to restrict a certain class to make more than a certain amount of instances. And if it is possible to make the compiler ("Eclipse") underline that line, when you try to make another instance (like it is an error in the code), or something along those lines?
Just to clarify for those who would say this is a bad idea, I am making a chess game, so I need it to not be able to make more than certain amount of playing pieces.
Eclipse can't do that at compile time, because it can't tell how many times a piece of code will be executed, and thus how many instances are created.
But you can design your class to only create a given number of instances, and make it impossibale to create more. For example:
public class Limited {
public static final List<Limited> ALL_INSTANCES =
Collections.unmodifiableList(createInstances());
private int id;
private static List<Limited> createInstances() {
List<Limited> result = new ArrayList<>();
for (int i = 0; i < 10; i++) {
result.add(new Limited(i));
}
}
private Limited(int id) {
this.id = id;
}
}
Since the constructor is private, the only 10 instances available are the ones in ALL_INSTANCES.
That said, that is not necessarily a good idea. Let's say you're creating a chess game. So by your logic, you shouldn't be able to create more than 2 King instances. What if your app handles 10 games at a time? Do you really want at most 2 Kings, or do you just want each ChessGame instance to have a black and a white King? Maybe all you need is something like
public class ChessGame {
private King blackKing = new King(BLACK);
private King whiteKing = new King(WHITE);
...
}
You can simply create the required number of objects - say by instantiating your class within a loop and then set a flag which is checked by the constructor so as to throw exception when an attempt is made to create one more. You can make the constructor private and have a static method to generate your instances.
New to Java-
I'm building a poker program and I've created a player class with some instance variables including "toppair", "highcardst",etc... I tried to use a placeholder variable to refer to the appropriate player's instance variable rather than relying on if statements.
int handsdealt=0;
int straightval=0;
String placeholder="blank";
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
if (handsdealt==1) placeholder="playerone";
else placeholder="playertwo";
//code to determine if hand is a straight -if it is it sets straightval to 1
**if(straightval==1) placeholder.highcardst=straightHigh;**
I receive an error on that last line- it looks like java doesn't accept this syntax. Essentially, since this hand is a straight I want to append the value of the "highcardst" instance variable of the "n" th player as n hands have been dealt.
Thank you.
You seem to be uses a String for your placeholder variable where you actually want to refer to a player object.
player playerone = new player("Richard");
player playertwo = new player("Negreanu");
//code omitted
player placeholder;
if (handsdealt==1) placeholder=playerone;
else placeholder=playertwo;
//code to determine if hand is a straight -if it is it sets straightval to 1
if(straightval==1) placeholder.highcardst=straightHigh;
Also, it will make your code easier to follow if you follow normal Java code conventions, such as capitalising the first letter of a class name (e.g. Player, not player).
You could make a list of players and get the instance of the player from the list as required.
List<player> players = new ArrayList<player>();
players.add(new player("Richard"));
players.add(new player("Negreanu"));
if(straightval==1) {
players.get(handsdealt).highcardst=straightHigh;
}
Or something like that.
I think the problem could be in this statement:
placeholder.highcardst=straightHigh;
You've defined placeholder of type String, so the property called highcardst does not exist.
if(straightval==1) placeholder.highcardst=straightHigh;
Error is here. place holder is String type not Player type. Make temp variable as Player variable and assign
Player placeholder;
if (handsdealt==1) placeholder=playerone;
Say i let players create teams and creating a team calls a new instance of the team class which has an array list called members.
Now in the main class how would i add a player to a team after being invited? i have an addPlayer method in the team class that simply add them to the arraylist but what if there are currently multiple instances of the teams class(other players have created teams) how would it know which one to join?
I do have a variable in the Teams class for the teamLeader which gets set when creating the instance if that could help me edit a certain instance.
Team team = new Team(this, leader);
Any help is appreiciated
You need an identifier to uniquely distinguish each team and you can use that identifier to store the teams in a Map. Something like this:
Map<String,Team> teamMap = new HashMap<String,Team>();
Chose the key type as per your requirement, I chose String for an example
As per your design, You need to keep all teams in a list after creation.
ArrayList teamsList=new ArrayList ();
Team team = new Team(this, leader);
teamsList.add(team);
Then Loop through all teams in addPlayer method and then compare leader and then add a player to it. Something like this -
public void addPlayer (Player player,String leader){
for(int i=0; i<teamListSize;i++)
Team tempTeam=teamsList.get(i);
if(tempTeam.getLeader().equalsIgnoreCase(leader)){
tempTeam.add(player);
break;
}
}