-1

Well I was trying to make a method that will add automatically a string to an array but with no clue.

Here is what I have so far :

        public static void addToArray(JTextField field , String[] strings) {

        String text = field.getText();
        strings.add(text);

}

But this does not work, what should I do?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Boolena
  • 225
  • 1
  • 2
  • 10
  • 1
    "...does not work" is not a problem statement. When you ask a question here, state *specifically* what the problem is, and include any error messages you are getting. – Robert Harvey Mar 11 '14 at 17:29
  • Google for "Java tutorial arrays". Arrays have a fixed length. If you don't know that yet, don't even think about using Swing, which is too complex for you at the moment. Go step by step and start with simple exercises not involving a GUI. – JB Nizet Mar 11 '14 at 17:30

3 Answers3

2

You need to pass an ArrayList instead of passing regular array like:

public static void addToArray(JTextField field, ArrayList<String> strings) {

    String text = field.getText();
    strings.add(text);
}
Salah
  • 8,567
  • 3
  • 26
  • 43
  • @Boolena lool its ok, it happened, and please don't forget to select this as answer if it solved your problem :). – Salah Mar 11 '14 at 17:39
1

An array in Java is of fixed size and you cannot add additional items to it. If you want a dynamic array, use List<String> instead of String[]

SiN
  • 3,704
  • 2
  • 31
  • 36
0

See here for why even using an ArrayList doesn't work.

In short, Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references and those references are passed by value.

It goes like this:

public void foo(Dog d) {
  d.getName().equals("Max"); // true
  d = new Dog("Fifi");
  d.getName().equals("Fifi"); // true
}

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Max"); // true

In this example aDog.getName() will still return "Max". d is not overwritten in the function as the object reference is passed by value.

Likewise:

public void foo(Dog d) {
  d.getName().equals("Max"); // true
  d.setName("Fifi");
}

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true
Community
  • 1
  • 1
GreySwordz
  • 368
  • 1
  • 9
  • Pass an ArrayList to the method, but make sure it returns an ArrayList so you can do do myArrayList = addToArray(JTextField field, myArrayList); – GreySwordz Mar 12 '14 at 11:56