Question

I am new to JAVA. I am working on priority queue. Suppose some how I ended up with these 4 variables with respective values, a1=2, a2=-4, a3=-8 and a4=10; Now I want to sort them in according to ascending order. By sorting or by priority Queue I know how to get the values in ascending order but how is it possible to get the variable name instead in JAVA? Like in this case the it would sort the variable names like this way [a3,a2,a1,a10]. Then I will take a3, a2 and so on and put them to other task. I am interested in getting the variable names rather than value. Is is possible?

Was it helpful?

Solution

how is it possible to get the variable name instead in JAVA?

No, it is not possible. The closest thing you could do is to store the variables and their values in a Map<String, Object> and assign the name of the variable as the key:

//maintain order of the elements by the key
Map<String, Integer> mapVariables = new TreeMap<String, Integer>();
mapVariables.put("a1", a1);
mapVariables.put("a2", a2);
mapVariables.put("a3", a3);
mapVariables.put("a4", a4);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top