Iterate through Instances Java

Do you need to to keep track of all the instances of your class? Do you need to iterate through all the instances of your class. Once I need to. Here we will save all the instances in a static array.
This method is considered as Bad Design. If you can find any other solution solve it that way.
Iterate through instance Java


Iterate through Instances

Here is a simple Token class. We keep track of all the instances while creating and letter look through all the created instances to check a simple condition and reset that token if it does.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//A simple Token class
public class Token {
    static List allCreatedTokens = new ArrayList();

    public Color color;
    public int location;
    public int id;

    public static Token createToken(Color color, int location, int id){
        Token aToken = new Token(color, id, location);
        allCreatedTokens.add(aToken);
        return aToken;
    }

    private Token(Color color, int id, int location) {
        this.color = color;
        this.id = id;
    }

    public void goHome(){
        for(Token token : allCreatedTokens){
            if(token.id != id){
                if(token.location == location
                token.reset();
            }
        }
    }

    public void reset(){

    }

    void kill() {
        allCreatedTokens.remove(this);
    }
}
Here we create a static method called createToken(). Here we pass all the required parameters for object creation. Then in this method we create a object of the Token class and add it in the static Array allCreatedTokens. Now we have all the created tokens stored in this Array. We can access all the instances as needed.
In the goHome() method. We compare current token with all the other tokens that were created. And reset the token to its original state.
Storing all the instances would cause memory leakage since those objects will never be disposed of, since the list will still be referencing them. We need to call the kill() method in that instance you no longer need to remove it from the list and thus Garbage Collector can remove it.
Other option could be to create a separate manager class.

Conclusion

With tracking all the instances in a static array list, and as it is stored in Array we can iterate through it. Thank you!


<<<Previous

0 Comments