-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)

11
  • 1
    How is the question related to selenium? Commented Sep 25, 2018 at 11:09
  • 1
    ArrayList<String> x.get(i) = new ArrayList<String>(); doesn't compile... Commented Sep 25, 2018 at 11:12
  • 1
    The code you posted is invalid (it produces compiler errors) and it is not clear what exactly your question is. Please edit your question, post valid code, and explain more clearly what exactly your question is. Commented Sep 25, 2018 at 11:12
  • Why not using a hashmap? Commented Sep 25, 2018 at 11:13
  • 1
    @Saravanan selenium is a testing framework how is this question related to that ? Commented Sep 25, 2018 at 11:15

3 Answers 3

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");
Sign up to request clarification or add additional context in comments.

Comments

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>());
}

Comments

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<>());
//      }
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.