Search code examples
arrayslibgdx

Libgdx - How to get a specific item from an array?


I have a Player class which has

int number;

In main, I store them in Array.

Array<Player> players;

How can I get a player which has for example number=2?


Solution

  • This question is programming in general, and has several ways to do what you say, I recommend you look for OOP.

    a solution, general, would encapsulate the variable, "creating getter and setter, you need, eg:

    this a simple class;

    private int number;
    
    public Player(int num){
       this.number = num;
    }
    
    public int getNumber (){
       return number;
    }
    
    public void setNumber (int n){
       this.number = n;
    }
    

    . In your code for search you can use the solution, using a for, or an iterator

    for (int a = 0; a < players.size(); a++){
    
        int tmpNumber = players.get(a).getNumber();
    
        if(tmpNumber == 2){
          players.get(a); //the object array with index equal to 
                          //the value of 'a', have, number 2 stored 
                          //in the variable 'number'
        }
    }
    

    but this question I think is a little matter of taste or needs you have