向数组添加元素?

时间:2009-11-30 19:46:24

标签: java arrays

这里我试图向数组中添加元素。 我想添加的元素是文本字段,所以我基本上试图在数组列表中存储人员的联系方式?

任何帮助都会很棒

public void addContact()
{
    ArrayList<String> details = new ArrayList<String>();
    {
        details.get(txtname(0));
        details.get(txtnum(1));
        details.get(txtmob(2));
        details.get(txtadd1(3));
    }        
}

8 个答案:

答案 0 :(得分:7)

听起来你还没有想到整个问题。

在Java中向ArrayList添加元素是这样的:

public void addContact(){
    ArrayList<String> foo = new ArrayList<String>();
    foo.add("HELLO");
    foo.add("WORLD");
}

答案 1 :(得分:2)

yankee2905解释得非常好;这就是使代码与ArrayList一起工作所需的。

作为旁注,你没有处理数组,你正在处理一个ArrayList。对于数组,您可能会这样:

String[] details = new String[4];
details[0] = "First";
details[1] = "Second";
details[2] = "Third";
details[3] = "Last";

答案 2 :(得分:1)

听起来您似乎正在尝试使用ArrayList来存储多人的联系信息。如果是这种情况,您可能希望以不同的方式做到这一点。您可以创建一个Contact对象,其中包含您要存储的每条信息的成员(例如,firstname,lastname,phone,mobile,address1,address2等)。然后,您只需将Contact对象添加到ArrayList,如:

  

联络contact1 = new联络();

     

contact1.setFirstname( “鲍勃”);

     

myArrayList.add(contact1);

答案 3 :(得分:0)

您需要设置或添加,而不是获取。请参阅文档here

要从textfields获取文本,请使用getText。

所以你有类似的东西:

myArrayList.add(myTextField.getText());

答案 4 :(得分:0)

您正在尝试使用内置数组初始化程序语法。这不适用于容器类(除非它在c#中有一些新的方式)你需要使用details.add()(或相应的成员函数)。

您尝试使用的语法是支持语言的硬连线数组类型。在C ++中,这看起来像char x[6] = {'h','e','l','l','o'};。但是容器不是一个容器对象的数组。容器对象通常通过重载operator[]来模仿数组,但是它们在幕后使用不同的数据结构 - 即它们不使用连续的内存区域。

p.s。,如果这是我最初假设的c#.NET - 有一种新的机制可以将数组初始化映射到容器对象创建。对于任何有兴趣的人,我会把它留在那里。

使用C# 3.5array initializer syntax

,您可以执行以下操作:

public void addContact()
{            
    ArrayList<String> details = new ArrayList<String>()
    {
        details.get(txtname(0)),
        details.get(txtnum(1)),
        details.get(txtmob(2)),
        details.get(txtadd1(3))
    }        
}

要爱微软和C#:P

答案 5 :(得分:0)

public void addContact()
        {
          ArrayList<String> details = new ArrayList<String>();
          {
          details.add(//Insert value from post here);
          details.add(//Insert value from post here);
          details.add(//Insert value from post here);
          details.add(//Insert value from post here);
          }        
        }

我暂时没有使用过java,也许有人会加入这个。

答案 6 :(得分:0)

public void addContact()
{
    ArrayList<String> details = new ArrayList<String>();
    details.add(txtname.getText());
    details.add(txtnum.getText());
    details.add(txtmob.getText());
    details.add(txtadd1.getText());        
}

抱歉,我没有打开IDE,但我认为这更接近你所追求的目标。

答案 7 :(得分:0)

如果你想创建一个包含一些元素的数组,我认为这是最好的解决方案:

String[] images = {"a.png","b.png","c.png"}; 

String[] images;    
images = new String[]{"a.png","b.png","c.png"};
相关问题