optimized the code with ArrayList and static method