Could there be a HashMap with 3 different types in Java?

I have a HashMap like

Map<String, JPanel> MapItems = new HashMap<String, JPanel>();

      

What if I want to put the third value and in a Map or List something like this

Map<String, JPanel, JLabel> MapItems = new HashMap<String, JPanel, JLabel>();

      

It doesn't matter if I need to call with the position of the element instead of the String value, so there is no need to use just a map, but if there is some other way please tell me. I just want to combine my JPanel

and JLabel

.

+3


source to share


4 answers


Create another object to wrap it and keep the JPanel and JLabel combination, something like this:

public class WrapperTest {

    private JPanel jPanel;
    private JLabel jLabel;

    public WrapperTest(JPanel jPanel, JLabel jLabel) {
        super();
        this.jPanel = jPanel;
        this.jLabel = jLabel;
    }

    public JPanel getjPanel() {
        return jPanel;
    }
    public void setjPanel(JPanel jPanel) {
        this.jPanel = jPanel;
    }
    public JLabel getjLabel() {
        return jLabel;
    }
    public void setjLabel(JLabel jLabel) {
        this.jLabel = jLabel;
    }

}

      

And use your hash like this:



Map<String, WrapperTest> mapItems = new HashMap<String, WrapperTest>();

      

Example:

public class Main {

    public static void main(String[] args) throws ParseException {

        JPanel jPanel1 = new JPanel();
        JLabel jLabel1 = new JLabel();

        WrapperTest wrapper1 = new WrapperTest(jPanel1, jLabel1);

        Map<String, WrapperTest> mapItems = new HashMap<String, WrapperTest>();
        mapItems.put("key1", wrapper1);

    }

}

      

+4


source


Here's another way. Create an object wrapper around JPanel

and JLabel

and use that as value.



class JWrapper {
    JPanel panel;
    JLabel label;
    // Constructor, getters, setters ...
}

// ...
HashMap<String, JWrapper> map = new HashMap<String, JWrapper>();
// ...

      

+3


source


No, not at all.

The purpose of a map is to match one thing to another: think of it as a source and destination, or a label on a box and the contents of a window. There is no room for a third "type of thing".

It is possible that you really want to map String

to a combination of the other two; in other words, you want to search for other values ​​with String

; you want to keep two things in a box. If so, you can do it, but you need to create a new Class panelAndLabel

one that contains two other elements. Then you can use that as the value type of your HashMap

.

(Or, for a quick hack, the value can be of type Object[]

or List<Object>

, and then you can put what you want in a value wrapper. But as I said, that would be a bit of a hack.)

+2


source


Guava has a nice data structure called Table for this purpose. Of course another option is for you to roll yourself, but I would use something in there.

+1


source







All Articles