-1
ArrayList<String> x = new ArrayList<String>(); 
for(int i = 0; i < x.size(); i++)
{
    ArrayList<String> x.get(i) = new  ArrayList<String>();
}

Both ArrayLists should be declared globally

The x ArrayList values are: server,buser,paer cook, runner, etc.

The first ArrayList value should be second ArrayList name(variable)

JeffC
  • 22,180
  • 5
  • 32
  • 55
Saravanan
  • 9
  • 1
  • 3

3 Answers3

4

It is not possible to set variable names dynamically in Java. If you still want to give some description to arrays of string you can create a Map for instance. i.e.

ArrayList<String> x = new  ArrayList<String>(); 
Map<String, ArrayList<String>> vars = new HashMap()<>;
for(int i = 0; i<x.size(); i++)
{
    vars.put(x.get(i),new  ArrayList<String>());
}

...

vars.get("server").add("Some Server info");
GiorgosDev
  • 1,757
  • 1
  • 14
  • 16
1

First typeof x isn't ArrayList<String>, it is ArrayList<ArrayList> because x's element is ArrayList

Second, you can't set element of ArrayList with ArrayList.get, you should use ArrayList.set

ArrayList<ArrayList> x = new ArrayList<>();

//todo something with size of `x` (if not x.size() = 0)
for (int i = 0; i < x.size(); i++) {
    x.set(i, new ArrayList<String>());
}
hong4rc
  • 3,999
  • 4
  • 21
  • 40
1

Try like this, You cannot create variable name dynamically.

public static void main(String[] args) {
        List<String> x = new ArrayList<>(Arrays.asList("server", "buser", "paer cook", "runner"));
        Map<String, ArrayList<String>> map = new HashMap<>();

//       if java version is 8
        x.forEach(eachElem -> {
            map.put(eachElem, new ArrayList<>());
        });

//      if java version is < 8
//      for(String eachElement : x ){
//          map.put(eachElement, new ArrayList<>());
//      }
    }
arjunan
  • 217
  • 1
  • 9