0

We can add a string to an ArrayList<String[]> as:

ArrayList<String[]> array1 = new ArrayList<>();
array1.add(new String[]{"word"});

But how can we add a string to an ArrayList<ArrayList<String[]>> directly without creating array1. Something like:

array2.add(new ArrayList<>(new String[]{"hello"}));
Dante
  • 457
  • 1
  • 5
  • 17
  • 1
    Why do you mix array with `List`s? Why not just one or the other (preferably: why not just `List`s)? – Turing85 May 05 '18 at 09:43
  • I am working with nlp. I am using an array to store word-tag combinations in an array (arraylist). But now, i have to process that array once again and add combinations of (word-tag),(word-tag)-tag . To put it simply, i want to make an arraylist, with arraylists as elements, but the last element, a string. – Dante May 05 '18 at 10:00

1 Answers1

3

You could use

array2.add(new ArrayList<>(Arrays.<String[]>asList(new String[]{"hello"})));

There is no ArrayList(ArrayOfElements) constructor, but we can use ArrayList(CollectionOfElementsToCopy) constructor. With that all we need to do is wrap elements into some collection. For that we can use Arrays.asList(elements).

Problem with Arrays.asList is that it uses T... varargs which by default represents array of elements. If we want to tell that array is element we can do it by explicitly specifying <String[]> as method generic type.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • I wouln't write such a code because it isn't really readable if the count of elements in the array raise, but for this problem it is a very elegant solution... +1 – 0x1C1B May 05 '18 at 09:47
  • Thank you. I wonder if there is a way we can use a string to represent the arraylist name. For example, ArrayList newArray = new ArrayList<>(); and in another array, ArrayList stringArray = new ArrayList<>(); now lets say stringArray has two strings-> string1,string2. Is it possible to somehow associate string1 to newArray and access its elements through string1? – Dante May 05 '18 at 10:10
  • @Dante For associating one thing with another we use maps. So you are probably looking for a `Map>>`. – Pshemo May 05 '18 at 10:18
  • @Dante Possibly related: [Get variable by name from a String](https://stackoverflow.com/q/13298823) – Pshemo May 05 '18 at 10:23
  • Thank you. This eased it out a lot :) – Dante May 05 '18 at 10:26