Yes, I know that's impossible; but the problem is that I really need to do it. I'll explain the whole trap:
public class MainMethods {
ArrayList arrayOfValues; // << PROBLEM
HashMap<String, Object> matrix = new HashMap<String, Object>();
void sendKeyToMatrix(String key) {
arrayOfValues = new ArrayList();
matrix.put(key, arrayOfValues);
}
void attachValueToKey(Object object, Object value) {
matrix.put((String) object, arrayOfValues.add(value));
}
void removeFromMatrix(String key) {
matrix.remove(key);
}}
That's my class and those are my methods. I created a HashMap with the key being a String and its value being an Object; pretty simple.
The real problem is with what I intend to do with this "Object" as a value. I have a GUI and a button that calls the "sendKeyToMatrix", and another one that attach a value to it, both from textFields. Since the ".put()" method for HashMaps requires an Object and I must create only the key first, the second argument is "null" or THE PROBLEM (ArrayList).
The perfect solution:
public class MainMethods {
HashMap<String, Object> matrix = new HashMap<String, Object>();
void sendKeyToMatrix(String key) {
ArrayList arrayOfValues = new ArrayList();
matrix.put(key, arrayOfValues);
}
void attachValueToKey(Object object, Object value) {
matrix.put((String) object, ghostOrigin.add(value));
}
void removeFromMatrix(String key) {
matrix.remove(key);
}}
When I call the "sendKeytoMatrix" with the button, it creates a key with an empty ArrayList as its value. This key is added to my JList. Then, when I call the second button (Considering what is selected in the JList), I add an element to the ArrayList:
Code for the second button:
btnInsertContent.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainMethods.attachValueToKey(mainList.getSelectedValue(), textContent.getText());
mainCombo.addItem(textContent.getText());
System.out.println(mainMethods.matrix);
}
});
The second argument of the "attachValueToKey" receives the String given by the textField, and I reach the big problem:
I can't add it to the ArrayList inside the "sendKeyToMatrix" method, which is obvious, but that's a big problem, because if I declare the variable as a field up there (So that I can access it down in the other scope), I get wrong and esoterically misterious results that are unknown to me.
Resuming this in a simple question: How to access the variable inside the other method?
If I declare the variable inside the "attachValueToKey", it will create an ArrayList inside of the ArrayList every time the button is pressed.
Well, I thank you all for the help. Probably there must be a way to summon the solution through Object Oriented Magic, with instances and the like.