Flub 1,281 Posted October 6, 2021 Report Share Posted October 6, 2021 Hey everyone. This is a better way to select a random entry from an enum An example of an enum group is: @AllArgsConstructor public enum SlayerTasks { DARKWIZARDS(SlayerMaster.SUMONA, 9203, "Find Darkblue Wizards at ::wizards", 1500, new Position(2903, 5203)), HEATED_PYRO(SlayerMaster.SUMONA, 172, "Heated Pyro can be found in the Elite Teleports", 1500, new Position(2863, 5354, 2)), PURPLE_WYRM(SlayerMaster.SUMONA, 9935, "Purple Wyrm can be found in the Elite Teleports", 1500, new Position(2602, 5713)), TRINITY(SlayerMaster.SUMONA, 170, "Trinity can be found in the Elite Teleports", 1500, new Position(2273, 4680, 1)), CLOUD(SlayerMaster.SUMONA, 169, "Cloud can be found in the Elite Teleports", 1500, new Position(1908, 4367)); private SlayerMaster taskMaster; private int npcId; private String npcLocation; private int XP; private Position taskPosition; } Enums are incredibly useful for storing multiple types of data. You'll see them used in a load of places! Now, the usual way to select a random entry from your enum list would be; SlayerTasks task = SlayerTasks.values()[Misc.random(SlayerTasks.values().length - 1)]; Of course - this does work. However, why not improve it! Here is a new method for you.. I've added mine into Misc.java along with my randomItem method! public static <T extends Enum<?>> T randomEnum(Class<T> clazz){ SecureRandom random = new SecureRandom(); int x = random.nextInt(clazz.getEnumConstants().length); return clazz.getEnumConstants()[x]; } Now, lets select a entry from our enum using this new method! (If added in Misc.java) SlayerTasks task = Misc.randomEnum(SlayerTasks.class); How much cleaner is that! You **must** add .class to the end of the name in this bracket. You can then use the entry as required! E.g. SlayerMaster master = task.taskMaster; int npcId = task.npcId; String npcLocation = task.npcLocation; int XP = task.XP; Position taskPosition = task.taskPosition; Hopefully you can use this to clean up some code 😛 Link to comment Share on other sites More sharing options...
0117be 66 Posted June 2, 2022 Report Share Posted June 2, 2022 You're on fire with these Link to comment Share on other sites More sharing options...
mire 0 Posted October 29, 2022 Report Share Posted October 29, 2022 Learning new tips and tricks as I just go down neat trick thank you Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now