Question

I have a fairly simple question, how would I name a variable using another variable.

For example:

public static void addSortListItem(int group_id) {
    if (lists.contains(group_id)) {
        // add item to correct array list 

    } else {
        lists.add(group_id);
        // create new array list using the group_id value as name identifier
        ArrayList<ExpListObject> group_id = new ArrayList<ExpListObject>();
    }       
  }

In this function I need to create a new arrayList using the group_id integer as the name. The error here is obviously a duplicate local variable, but what is the correct way to name this?

Any help is appreciated!

Was it helpful?

Solution

You are using group_id as both an identifier name and parameter name. That doesn't make sense. Instead, map the new ArrayList to the group_id. For example:

HashMap<Integer,ArrayList<ExpListObject>> hm = new HashMap<Integer,ArrayList<ExpListObject>>();
hm.put(group_id, new ArrayList<ExpListObject>());

OTHER TIPS

You can make something like this using HashMap, this way:

public static void addSortListItem(int group_id) {

    //Create a HashMap to storage your lists
    HashMap<String, ArrayList<ExpListObject>> mapList = new HashMap<String, ArrayList<ExpListObject>>();

    ArrayList<Object> array = mapList.get(String.valueOf(group_id));
    if (array != null) {
       array.add(new ExpListObject());
    } else {
       // Insert the new Array into the HashMap
       mapList.put(String.valueOf(group_id), new ArrayList<ExpListObject>());
    }       
}

Or this way:

public static void addSortListItem(int group_id) {

    //Create a HashMap to storage your lists
    HashMap< Integer, ArrayList<ExpListObject>> mapList = new HashMap< Integer, ArrayList<ExpListObject>>();

    ArrayList<Object> array = mapList.get(group_id);
    if (array != null) {
       array.add(new ExpListObject());
    } else {
       // Insert the new Array into the HashMap
       mapList.put(group_id, new ArrayList<ExpListObject>());
    }       
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top