I need to create a number of objects to populate an ArrayList. These objects need to be uniquely identified. I was hoping to let the user name the objects. When I go to pass the reference variable of the String to name the object, it is not allowed.

String input;
Object { input } = new Object();
arrayList.addObject( { input } );

If there is no way to dynamically name objects, how might I go about creating these objects?

有帮助吗?

解决方案 2

Object doesn't have a name field. You could create your own class and then add an instance of that class to your collection.

You could do this:

public class CustomItem
{
        private String name;

        public CustomItem(String n)
        {
            this.name = n;
        }

        public String getName()
        {
            return this.name;
        }
} 

And add it to your arrayList like this:

arrayList.add(new CustomItem("I1"));

If you wanted to check if a particular element of the collection matched some name, you would call the getName() method on that element and compare it some name.

其他提示

You're not trying to name an object; you're trying to name a variable. The solution is: don't. That's not how Java works. In Java, variable names really don't matter all that much and are almost non-existent in compiled code. Rather references are what matter. Instead use a Map<String, MyType> to associated a String with an object. A HashMap<String, SomeType> would work well here.

You likely dont want to use the Object class. Instead, you should make your own class (which automatically inherits from Object that has a String field called name. IE:

Class MyClass{
    myClass(String s){ name = s;}
    private String name;
}

Then you can do MyClass myClass = new MyClass(name-inputted-by-user); and add it to your array list. You will likely also want to override the equals function so that it compares names

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top