Vinoth
Vinoth

Reputation: 1349

Inserting data into an arraylist

My question is specific to Java. I have a Get and Set method that will get and set the data. I would like to add this into an arraylist. How can I do this ?

Below I've shown a small sample of what I've done so far.

public class GetSetMethod {

    String newcompanyid = null;

    public String getNewcompanyid() {
        return newcompanyid;
    }

    public void setNewcompanyid(String newcompanyid) {
        this.newcompanyid = newcompanyid;
    }
}

In my MainActivity I am using this object

    public class MainActivity{
       ArrayList<String> bulk = new ArrayList<String>();

       GetSetMethod  objSample = new GetSetMethod();

       objSample.setNewcompanyid(newcompanyid);
    }

How can I put the values of objSample into the array list. I've tried using

bulk.add(newcompanyid);

But since I've a large amount of data to be passed (and there is a for loop also), it calls the function many times.

Thanks for your help !

Upvotes: 2

Views: 14371

Answers (3)

Wilts C
Wilts C

Reputation: 1750

List<GetSetMethod> list = new ArrayList<GetSetMethod>();
GetSetMethod objSample = new GetSetMethod();
objSample.setNewcompanyid("Any string you want");
list.add(objSample);

Upvotes: 4

Luka Klepec
Luka Klepec

Reputation: 542

There is no way around it, if you want to add "large amount" of data to a List you will have a "large amount" of add() calls in your code.

Upvotes: 0

Heisenbug
Heisenbug

Reputation: 39174

Well, I think there is no other way than adding each element to the list. Just a few tips:

ArrayList<String> bulk = new ArrayList<String>();

you should replace the code above with:

List<String> bulk = new ArrayList<String>();

that allows you to switch between different List implementations(ArrayList, LinkedList, ...).

If the data to be added are already into another collection you can do the following instead of adding each element:

List<Integer> a;
List<Integer> b;

....

b.addAll(a);

In addition, if you need to initialize a List with a set of elements known at compile time, you can do the following:

List<String> list = Arrays.asList("foo", "bar");

Upvotes: 0

Related Questions