[Ruse] Improved Random Enum method!

Hey everyone.

Following the previous tutorial where I gave an improved random Item[] selection method… I’m here with one made for Enums!

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;

Hopfully you can use this to clean up some code :stuck_out_tongue:

Its Over GIF