user1816974
user1816974

Reputation: 29

Manipulation of Java String arrays

I have a situation like

String[] ids = new String[depts.size()];
for (int i=0; i<ids.length; i++)
{
  ids [i] = ("Dept" + .... )
}

So the loop looks at ids whose length is set to depts.size. But I need to add another string item to ids [i] like a "Region" + reg_num. Like the next item in ids[i] must be "Region" + reg_num and this is repeated for every department.
Since it is controlled by length, how do I do that? How do I adjust the loop to take 1 additional item. Any suggestions will be appreciated.

Thanks.

Upvotes: 0

Views: 109

Answers (4)

fge
fge

Reputation: 121710

Just use a List instead of an array. Unlike arrays, lists are dynamically resizable:

final List<String> newList = new ArrayList<>(oldList);
newList.add(newElement);

EDIT if you are still using Java 6 you'll have to:

final List<String> newList = new ArrayList<String>(oldList);

instead

EDIT 2 depending on your use case, you may not even need a second list; as lists are dynamically resizable, unless you absolutely need to copy it, just keep the same list:

// first call
list.add(something);
// second call
list.add(somethingElse);
// etc etc

Without seeing more of the code however, it's hard to tell.

Upvotes: 3

anubhava
anubhava

Reputation: 785128

If you are trying to store a department for each id then its better to define a custom class like this:

public class Region {
    String id;
    String dept;
    public Region(String id, String dept) {
        this.id=id;
        this.dept=dept;
    }
    // getters for id and dept
}

then define your region array like this

Region[] regions = new Region[depts.size()];
for (int i=0; i<regions.length; i++) {
  regions[i] = new Region("Dept"+i, "Region"+i);
}

Upvotes: 1

Yogendra Singh
Yogendra Singh

Reputation: 34367

If you know before hand then initialize the array accordingly and add the elements as:

   String[] ids = new String[depts.size()+1];//added one in the length
   for (int i=0; i<ids.length; i++)
   {
     ids [i] = ("Dept" + .... )
   }
   ids[ids.length-1] = "Region"+....; 

or

   String[] ids = new String[2*depts.size()];//added one in the length
   for (int i=0; i<ids.length; i=i+2)
   {
     ids [i] = ("Dept" + .... )
     ids[i+1] = "Region"+....; 
   }

Upvotes: 1

khachik
khachik

Reputation: 28693

If I understand your reqs correctly, you can do something like this (but remember that you can hold a list of strings instead of an array, to change it dynamically):

String[] ids = new String[depts.size()*2];
for (int i=0; i<ids.length; i+=2)
{
  // depts index would be i/2
  ids [i] = ("Dept" + .... )
  ids[i+1] = "Region"; // + ...
}

Upvotes: 0

Related Questions