0

I have a string that I have generated, and I need to add it to a String[] that I created before I generated the string. I tried this:

String[] operators = {};
string generatedString = /*generating string from JTextField values*/;
operators.append(generatedString);

And this:

String[] operators = {};
string generatedString = /*generating string from JTextField values*/;
append(operators, generatedString);

And this:

String[] operators = {};
string generatedString = /*generating string from JTextField values*/;
operators.add(generatedString);

But all of them show syntax errors. I feel like there should be a simple solution that I'm missing, but I can't find it.

Ethan JC Rubik
  • 174
  • 1
  • 1
  • 12

2 Answers2

1

Arrays in Java are of fixed size. You can use ArrayList:

ArrayList< String > str = new ArrayList< String >(); Then to change the list you use str.add(value).

You can see how to iterate through ArrayList here: http://googleweblight.com/?lite_url=http://tutorialswithexamples.com/java-arraylist-iterator-example/&ei=s6HaARD2&lc=en-IN&s=1&m=397&host=www.google.co.in&ts=1456544389&sig=ALL1Aj5nVY9uHxdh2RrQqin8ymdO3su14w

Aajan
  • 927
  • 1
  • 10
  • 23
  • 1
    Style comment: It's better to declare str as 'List' to separate the behavior from the implementation. – Lars Feb 27 '16 at 04:34
  • 1
    `ArrayList` use only when you don't know the size of array at the time of writing (Fixed). if you do not know what will be the size of array you must use the concept of Typical `java` Arrays Concept due to performance issue. Thank You – Vikrant Kashyap Feb 27 '16 at 04:45
1

What you need is an ArrayList. Java array is size-fixed.

ArrayList<String> operators = new ArrayList<String>();
string generatedString = /*generating string from JTextField values*/;
operators.add(generatedString);
Xiongbing Jin
  • 11,779
  • 3
  • 47
  • 41