java 将数据插入数组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7913084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:59:09  来源:igfitidea点击:

Inserting data into an arraylist

javaandroidarraylist

提问by Vinoth

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 ?

我的问题是针对 Java 的。我有一个 Get 和 Set 方法可以获取和设置数据。我想将它添加到一个数组列表中。我怎样才能做到这一点 ?

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

在我的 MainActivity 我使用这个对象

    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

如何将 objSample 的值放入数组列表中。我试过使用

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.

但是由于我要传递大量数据(并且还有一个 for 循环),它会多次调用该函数。

Thanks for your help !

谢谢你的帮助 !

回答by Wilts C

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

回答by Heisenbug

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

它允许您在不同的 List 实现(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,您可以执行以下操作:

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

回答by Luka Klepec

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.

没有办法解决它,如果您想向 List 添加“大量”数据,您的代码中将有“大量” add() 调用。