0

I would like to sort my list of variables, from largest to smallest, and then print out the names of the variables. I have already tried Arrays, but when printing the array out, it prints out the value of the variables, not the names.

  • 1
    Codes are thousand times more effective than 100 hundred words. Please post your code too. – Rohit Jain Sep 24 '13 at 15:23
  • 2
    @RohitJain this case is very simple: *print out the names of the variables*. This isn't possible. – Luiggi Mendoza Sep 24 '13 at 15:24
  • You can at least have a field on your *variables* that states its name and use it when printing the sorted array, but there's no way you can now the name of a variable at run time. – Luiggi Mendoza Sep 24 '13 at 15:25
  • Hi user2811760 - perhaps you could help us by giving an example of your input and expected output, and code you've tried. Even more helpful, explain your reasoning! – Meesh Sep 24 '13 at 15:27

2 Answers2

6

Printing out variable names lies somewhere between extremely tricky (on the order of hunting through .class files and hoping for the best) and downright impossible. If I were you, I'd use a Map instead, where you can map variable values to their "names" in the code, and then you can sort the keys and print the values in order.


The problems with accessing variable names are outlined well in the answers to the question I linked, but the basic issue is this: what if I have an object with no name defined for it? What if there's more than one name for a single object?

Community
  • 1
  • 1
Henry Keiter
  • 16,863
  • 7
  • 51
  • 80
0

As far as I know, You can't print the names of stack variables in java, as that data does not exist in runtime. You can wrap your variables in a class and override its toString() method. For Example, instead of

int x = 3;

use: public class Wrapper { private final int value; private final String name;

public Wrapper(int value, String name) {
    this.value = value;
    this.name = name;
}

public String getName() {
    return name;
}

public int getValue() {
    return value;
}
}

Wrapper x = new Wrapper(3, "x");
Gal
  • 5,338
  • 5
  • 33
  • 55