如何动态地向Java数组添加项?

时间:2022-06-23 07:00:34

In PHP, you can dynamically add elements to arrays by the following:

在PHP中,可以通过以下步骤将元素动态添加到数组中:

$x = new Array();
$x[] = 1;
$x[] = 2;

After this, $x would be an array like this: {1,2}.

在这之后,$x将是这样的数组:{1,2}。

Is there a way to do something similar in Java?

在Java中有类似的方法吗?

11 个解决方案

#1


100  

Look at java.util.LinkedList or java.util.ArrayList

看看java.util。LinkedList或java.util.ArrayList

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);

#2


63  

Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.

Java中数组的大小是固定的,所以不能像PHP中那样“添加一些东西”。

A bit similar to the PHP behaviour is this:

有点类似于PHP的行为:

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;
}

Then you can write:

然后你可以写:

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);

System.out.println(Arrays.toString(x));

But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).

但是这个方案对于更大的数组来说是非常低效的,因为它每次都会复制整个数组。(实际上它并不完全等同于PHP,因为您的旧数组保持不变)。

The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.

PHP数组实际上与添加了“max key”的Java HashMap是完全相同的,因此它知道接下来使用哪个键,以及奇怪的迭代顺序(以及整数键和一些字符串之间奇怪的等价关系)。但是对于简单的索引集合,最好使用Java中的列表,就像其他答案者建议的那样。

If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)

如果您想避免使用List,因为将每个int类型封装在一个整数中会产生开销,那么可以考虑为基本类型使用集合的重新实现,这些基本类型在内部使用数组,但只有在内部数组已满时(就像ArrayList一样),才会对每个更改进行复制。(一个很快被google搜索到的例子是IntList类。)

Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.

番石榴包含在Ints中创建此类包装器的方法。asList,多头。asList等等。

#3


17  

Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:

Apache Commons有一个ArrayUtils实现,在新数组的末尾添加一个元素:

/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)

#4


11  

You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.

您可以使用ArrayList,然后使用toArray()方法。但是根据您正在做的操作,您甚至可能根本不需要一个数组。看看列表是否更符合你的要求。

See: Java List Tutorial

看到:Java教程列表

#5


8  

I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.

我经常在网上看到这个问题,在我看来,很多有名望的人没有正确地回答这些问题。所以我想在这里表达我自己的答案。

First we should consider there is a difference between array and arraylist.

首先,我们应该考虑数组和arraylist之间的区别。

The question asks for adding an element to an array, and not ArrayList

这个问题要求将一个元素添加到数组中,而不是ArrayList。


The answer is quite simple. It can be done in 3 steps.

答案很简单。它可以分为三个步骤。

  1. Convert array to an arraylist
  2. 将数组转换为arraylist
  3. Add element to the arrayList
  4. 添加元素到arrayList。
  5. Convert back the new arrayList to the array
  6. 将新的arrayList转换回数组

Here is the simple picture of it 如何动态地向Java数组添加项?

这是它的简单图片。

And finally here is the code:

最后是代码:

Step 1:

步骤1:

public List<String> convertArrayToList(String[] array){
        List<String> stringList = new ArrayList<String>(Arrays.asList(array));
        return stringList;
    }

Step 2:

步骤2:

public  List<String> addToList(String element,List<String> list){

            list.add(element);
            return list;
    }

Step 3:

步骤3:

public String[] convertListToArray(List<String> list){
           String[] ins = (String[])list.toArray(new String[list.size()]);
           return ins;
    } 

Step 4

步骤4

public String[] addNewItemToArray(String element,String [] array){
        List<String> list = convertArrayToList(array);
        list= addToList(element,list);
        return  convertListToArray(list);
}

#6


5  

You probably want to use an ArrayList for this -- for a dynamically sized array like structure.

您可能想要使用一个ArrayList——对于一个动态大小的数组,比如结构。

#7


4  

You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.

您可以使用JAVA中的集合框架动态地向数组添加元素。集合框架不能处理原始数据类型。

This Collection framework will be available in "java.util.*" package

这个集合框架将在“java.util”中可用。*”包

For example if you use ArrayList,

例如,如果你使用ArrayList,

Create an object to it and then add number of elements (any type like String, Integer ...etc)

为它创建一个对象,然后添加一些元素(任何类型,如字符串、整数等等)

ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");

Now you were added 3 elements to an array.

现在将3个元素添加到一个数组中。

if you want to remove any of added elements

如果您想删除任何添加的元素

a.remove("suman");

again if you want to add any element

如果你想添加任何元素。

a.add("Gurram");

So the array size is incresing / decreasing dynamically..

所以数组大小是动态增加/减少的。

#8


1  

Use an ArrayList or juggle to arrays to auto increment the array size.

使用ArrayList或变通数组来自动增加数组大小。

#9


0  

keep a count of where you are in the primitive array

对原始数组中的位置进行计数

class recordStuff extends Thread
{
    double[] aListOfDoubles;
    int i = 0;

    void run()
    {
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());
    }

    void doStuff()
    {
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
        {
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
            {
                if (a[j] == a[i]) count++;
            }
            if (count > maxCount) 
            {
                maxCount = count;
                maxValue = aListOfDoubles[i];
            }
        }
        return maxValue;
    }
}

#10


0  

This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.

这是在java中添加数组的一种简单方法。我使用了第二个数组来存储原始数组,然后向它添加了一个元素。之后,我将该数组传递回原始数组。

    int [] test = {12,22,33};
    int [] test2= new int[test.length+1];
    int m=5;int mz=0;
    for ( int test3: test)        
    {          
    test2[mz]=test3; mz++;        
    } 
    test2[mz++]=m;
    test=test2;

    for ( int test3: test)

    {
      System.out.println(test3);
    }

#11


0  

In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.

在Java中,数组的大小是固定的,但是您可以使用它的索引和for循环将元素动态地添加到一个固定大小的数组中。请查收下面的例子。

package simplejava;

import java.util.Arrays;

/**
 *
 * @author sashant
 */
public class SimpleJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        try{
            String[] transactions;
            transactions = new String[10];

            for(int i = 0; i < transactions.length; i++){
                transactions[i] = "transaction - "+Integer.toString(i);            
            }

            System.out.println(Arrays.toString(transactions));

        }catch(Exception exc){
            System.out.println(exc.getMessage());
            System.out.println(Arrays.toString(exc.getStackTrace()));
        }
    }

}

#1


100  

Look at java.util.LinkedList or java.util.ArrayList

看看java.util。LinkedList或java.util.ArrayList

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);

#2


63  

Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.

Java中数组的大小是固定的,所以不能像PHP中那样“添加一些东西”。

A bit similar to the PHP behaviour is this:

有点类似于PHP的行为:

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;
}

Then you can write:

然后你可以写:

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);

System.out.println(Arrays.toString(x));

But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).

但是这个方案对于更大的数组来说是非常低效的,因为它每次都会复制整个数组。(实际上它并不完全等同于PHP,因为您的旧数组保持不变)。

The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.

PHP数组实际上与添加了“max key”的Java HashMap是完全相同的,因此它知道接下来使用哪个键,以及奇怪的迭代顺序(以及整数键和一些字符串之间奇怪的等价关系)。但是对于简单的索引集合,最好使用Java中的列表,就像其他答案者建议的那样。

If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)

如果您想避免使用List,因为将每个int类型封装在一个整数中会产生开销,那么可以考虑为基本类型使用集合的重新实现,这些基本类型在内部使用数组,但只有在内部数组已满时(就像ArrayList一样),才会对每个更改进行复制。(一个很快被google搜索到的例子是IntList类。)

Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.

番石榴包含在Ints中创建此类包装器的方法。asList,多头。asList等等。

#3


17  

Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:

Apache Commons有一个ArrayUtils实现,在新数组的末尾添加一个元素:

/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)

#4


11  

You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.

您可以使用ArrayList,然后使用toArray()方法。但是根据您正在做的操作,您甚至可能根本不需要一个数组。看看列表是否更符合你的要求。

See: Java List Tutorial

看到:Java教程列表

#5


8  

I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.

我经常在网上看到这个问题,在我看来,很多有名望的人没有正确地回答这些问题。所以我想在这里表达我自己的答案。

First we should consider there is a difference between array and arraylist.

首先,我们应该考虑数组和arraylist之间的区别。

The question asks for adding an element to an array, and not ArrayList

这个问题要求将一个元素添加到数组中,而不是ArrayList。


The answer is quite simple. It can be done in 3 steps.

答案很简单。它可以分为三个步骤。

  1. Convert array to an arraylist
  2. 将数组转换为arraylist
  3. Add element to the arrayList
  4. 添加元素到arrayList。
  5. Convert back the new arrayList to the array
  6. 将新的arrayList转换回数组

Here is the simple picture of it 如何动态地向Java数组添加项?

这是它的简单图片。

And finally here is the code:

最后是代码:

Step 1:

步骤1:

public List<String> convertArrayToList(String[] array){
        List<String> stringList = new ArrayList<String>(Arrays.asList(array));
        return stringList;
    }

Step 2:

步骤2:

public  List<String> addToList(String element,List<String> list){

            list.add(element);
            return list;
    }

Step 3:

步骤3:

public String[] convertListToArray(List<String> list){
           String[] ins = (String[])list.toArray(new String[list.size()]);
           return ins;
    } 

Step 4

步骤4

public String[] addNewItemToArray(String element,String [] array){
        List<String> list = convertArrayToList(array);
        list= addToList(element,list);
        return  convertListToArray(list);
}

#6


5  

You probably want to use an ArrayList for this -- for a dynamically sized array like structure.

您可能想要使用一个ArrayList——对于一个动态大小的数组,比如结构。

#7


4  

You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.

您可以使用JAVA中的集合框架动态地向数组添加元素。集合框架不能处理原始数据类型。

This Collection framework will be available in "java.util.*" package

这个集合框架将在“java.util”中可用。*”包

For example if you use ArrayList,

例如,如果你使用ArrayList,

Create an object to it and then add number of elements (any type like String, Integer ...etc)

为它创建一个对象,然后添加一些元素(任何类型,如字符串、整数等等)

ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");

Now you were added 3 elements to an array.

现在将3个元素添加到一个数组中。

if you want to remove any of added elements

如果您想删除任何添加的元素

a.remove("suman");

again if you want to add any element

如果你想添加任何元素。

a.add("Gurram");

So the array size is incresing / decreasing dynamically..

所以数组大小是动态增加/减少的。

#8


1  

Use an ArrayList or juggle to arrays to auto increment the array size.

使用ArrayList或变通数组来自动增加数组大小。

#9


0  

keep a count of where you are in the primitive array

对原始数组中的位置进行计数

class recordStuff extends Thread
{
    double[] aListOfDoubles;
    int i = 0;

    void run()
    {
        double newData;
        newData = getNewData(); // gets data from somewhere

        aListofDoubles[i] = newData; // adds it to the primitive array of doubles
        i++ // increments the counter for the next pass

        System.out.println("mode: " + doStuff());
    }

    void doStuff()
    {
        // Calculate the mode of the double[] array

        for (int i = 0; i < aListOfDoubles.length; i++) 
        {
            int count = 0;
            for (int j = 0; j < aListOfDoubles.length; j++)
            {
                if (a[j] == a[i]) count++;
            }
            if (count > maxCount) 
            {
                maxCount = count;
                maxValue = aListOfDoubles[i];
            }
        }
        return maxValue;
    }
}

#10


0  

This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.

这是在java中添加数组的一种简单方法。我使用了第二个数组来存储原始数组,然后向它添加了一个元素。之后,我将该数组传递回原始数组。

    int [] test = {12,22,33};
    int [] test2= new int[test.length+1];
    int m=5;int mz=0;
    for ( int test3: test)        
    {          
    test2[mz]=test3; mz++;        
    } 
    test2[mz++]=m;
    test=test2;

    for ( int test3: test)

    {
      System.out.println(test3);
    }

#11


0  

In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.

在Java中,数组的大小是固定的,但是您可以使用它的索引和for循环将元素动态地添加到一个固定大小的数组中。请查收下面的例子。

package simplejava;

import java.util.Arrays;

/**
 *
 * @author sashant
 */
public class SimpleJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        try{
            String[] transactions;
            transactions = new String[10];

            for(int i = 0; i < transactions.length; i++){
                transactions[i] = "transaction - "+Integer.toString(i);            
            }

            System.out.println(Arrays.toString(transactions));

        }catch(Exception exc){
            System.out.println(exc.getMessage());
            System.out.println(Arrays.toString(exc.getStackTrace()));
        }
    }

}