user2811760
user2811760

Reputation:

How can I sort variable values, and then print them in order, largest to smallest?

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.

Upvotes: 0

Views: 320

Answers (2)

Henry Keiter
Henry Keiter

Reputation: 17168

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?

Upvotes: 6

Gal
Gal

Reputation: 5416

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");

Upvotes: 0

Related Questions