0

I'm working on a program that reverses a string by words and I have 2 vectors, words(the words but reversed, which is initiated with the words) and words2(the words, it's not initiated and I want to add the words). Is there any function that can add a String into a String[]?

alexzimmer96
  • 996
  • 6
  • 14
Ultra
  • 3
  • 2
  • It seems like a dynamic data type like ArrayList is more suitable here, but if you really want to have arrays, maybe the ArraysUtils library is useful https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#add-T:A-T- – thinkgruen Aug 04 '21 at 09:26
  • `String[]` isn't a string vector, but a string array which has fixed length, it would be better to show your code; because in that case both would have same size so you stick to arrays for that case – azro Aug 04 '21 at 09:27

2 Answers2

0

Check out this answer.

In short, an array in Java cannot be resized. If you want to add an element, you would need to create a new bigger array and copy the contents from the array you have, or use a different container more suitable to your needs.

lnstadrum
  • 550
  • 3
  • 15
0

A primitive array has a fixed size once you instantiate it. Unless you have a very specific need to use a primitive array, you can use an ArrayList and just add and remove elements from it.

List<String> yourList = new ArrayList<>();
yourList.add("foo");
System.out.println(yourList.get(0));

This will add the string foo at the end. See https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

Dropout
  • 13,653
  • 10
  • 56
  • 109
  • Well I can't do `ArrayList words = text1.split("\\s");` so I need to use a vector – Ultra Aug 04 '21 at 15:25
  • Nobody can, because `String::split` produces a primitive array. You need to do `ArrayList words = Arrays.asList(text1.split("\\s"))` Still no reason to use a primitive array. – Dropout Aug 05 '21 at 11:42