Warm tip: This article is reproduced from serverfault.com, please click

How to change the displayed name of an object in an ArrayList

发布于 2020-11-28 03:29:39

I want to change an element name in an ArrayList, without changing its value. Like :-

ArrayList<Integer> array1 = new ArrayList<>();
int num = 1;
array1.add(num);

Now I want to change num to number, but it's value will be 1. (Is it possible?)

I want to display all the elements in a ArrayList in a swing combo box, but some of the variables show strange names, such as "Client@45673...". But I want the user to see a descriptive name. That is why I want to rename the variables.

Questioner
BoomCode 10010011
Viewed
1
Stephen C 2020-11-28 12:47:30

OK, so you are wandering up the proverbial garden path with your "change the name of a variable".

Firstly, it is not a variable. When you put something into a collection, Java doesn't remember that at one point you had the value in a variable.

Secondly, values in general and objects in particular don't have names ... unless you specifically implemented some kind of "name" field as part the class definition.

But I think the clue is in this sentence:

... but some of the variables show strange names, such as "Client@45673..."

That's not a name! That looks like the output of the default implementation1 of toString that your Client class is inheriting from java.lang.Object.

If you want to print / display something something more meaningful, your Client class needs to override the toString() method with its own implementation.

For example:

public class Client {
    private String myDescription;

    public Client(...) {
        ...
        myDescription = /* something */
    }

    @Override
    public String toString() {
        return myDescription;
    }
}

Your toString method can return anything you want it to ... so long as it is represented as a string.

Incidentally, if you were to print the array1 object in your question, you would see the actual value 1 rather than a "name" (as you called it). This is because java.lang.Integer overrides the toString() method.


1 - The default toString() result consists of the internal class name and the object's identity hashcode value. The latter is a magic number that the JVM generates. It is not guaranteed unique, but it is guaranteed that it won't change for the lifetime of the object. At any rate, you cannot alter the string that is generated by that method ... except by overriding it.