2

I have two classes, A and B.

B contains the instances of A. I want to return instance of A from B by its name:

class A
{
    public String name;

    public A (String name)
    {
        this.name = name;
    }
}

class B
{
    public A a1;
    public A a2;
    public A a3;

    public B ()
    {
        this.a1 = new A ("a1");
        this.a2 = new A ("a2");
        this.a3 = new A ("a3");
    }

    public A get_A_byName (String name)
    {
        // Is it possible to write something like this? B will always contain only instances of A
        for (A a : B.variables)
        {
            if (a.name.equals(name))
            {
                return a;
            }

            // Or in case A doesn't have a variable "name", can I get an A instance by its declared name in B?
            if (a.getClass().getName().equals(name))
            {
                return a;
            }
        }
    }
}

Is it possible to do things described in code's comments? Thanks in advance.

Niklas
  • 13,005
  • 23
  • 79
  • 119
jirinovo
  • 2,105
  • 3
  • 26
  • 37

1 Answers1

5

This is more or less what hashmaps were made for, for pairing a key (in this case a string) to an object

class B
{
    private HashMap<String,A> theAs=new HashMap<String,A>(); //give better name


    public B ()
    {
        theAs.put("a1",new A ("a1")); //A probably doesn't need to keep its own name internally now, but have left it as its in your original code
        theAs.put("a2",new A ("a2"));
        theAs.put("a3",new A ("a3"));
    }

    public A get_A_byName (String name)
    {
        return theAs.get(name);
    }
}

Notes

  • In Java 7+ you don't need to add the second <String,A>, diamond inference will do, so in Java 7 or higher it would be:

    private HashMap<String,A> theAs=new HashMap<>();
    
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
  • The reason why I'm not using HashMap is that I want the A instances in B to be directly accesible by dot, e.g. B.a1 | But it seems I need to also implement that HashMap. Thanks – jirinovo Apr 29 '14 at 11:46
  • @user1928742 As a general rule you don't want fields accessable directly anyway (except for very simple 'struct like' objects). You loose encapsulation and bugs creep in – Richard Tingle Apr 29 '14 at 11:47