Reputation:
I have a HashMap like
Map<String, JPanel> MapItems = new HashMap<String, JPanel>();
What if I want to put third value as well in a Map or List something like this
Map<String, JPanel, JLabel> MapItems = new HashMap<String, JPanel, JLabel>();
it doesn't matter if I have to call with element position instead String Value so it isn't necessary to use Map only but if there is some other way around please tell me. I just want to put my JPanel
and JLabel
together.
Upvotes: 3
Views: 1826
Reputation: 2037
Create another Object to wrap it and save the combination of your JPanel and JLabel, something like that:
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 this way:
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);
}
}
Upvotes: 4
Reputation: 20520
No, not really.
The purpose of a map is to map from one thing to another: think of it as a source and a destination, or a label on a box and the contents of the box. There isn't room for a third "type of thing" in there.
It might be that what you really want is to map the String
onto a combination of the other two; in other words, you want to look up both of the other values using the String
; you want to store two things in the box. If so, you can certainly do that, but you need to create a new Class panelAndLabel
that contains the other two items. You can then use that as the value type of your HashMap
.
(Or, for a quick hack, the value could be of type Object[]
, or List<Object>
, and then you could put what you want into the value wrapper. But, as I say, that would be a bit of a hack.)
Upvotes: 2
Reputation: 35491
Here is another way. Make an object wrapper around JPanel
and JLabel
and use that as the value.
class JWrapper {
JPanel panel;
JLabel label;
// Constructor, getters, setters ...
}
// ...
HashMap<String, JWrapper> map = new HashMap<String, JWrapper>();
// ...
Upvotes: 3
Reputation: 38541
Guava has a nice data structure called a Table, for exactly this purpose. Of course, another option is for you to roll your own, but I would use whats out there.
Upvotes: 1