如何动态地将项目添加到 Java 数组中?

发布于 2024-10-18 14:11:17 字数 187 浏览 3 评论 0原文

在 PHP 中,您可以通过以下方式动态地将元素添加到数组中:

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

此后,$x 将是一个如下所示的数组:{1,2}

有没有办法在Java中做类似的事情?

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

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

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

Is there a way to do something similar in Java?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

高速公鹿 2024-10-25 14:11:17

查看 java.util.LinkedList 或 java.util.ArrayList

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

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

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
罪歌 2024-10-25 14:11:17

Java 中的数组具有固定大小,因此您无法像 PHP 中那样“在末尾添加一些内容”。

与 PHP 的行为有点相似的是:

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

然后你可以这样写:

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

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

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

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

如果您想避免使用 List 因为将每个 int 包装在 Integer 中的开销,请考虑使用原始类型集合的重新实现,它在内部使用数组,但不会在每次更改时进行复制,仅当内部数组已满时(就像 ArrayList 一样)。 (在谷歌上快速搜索到的一个示例是这个 IntList 类。 )

Guava 在 Ints 中包含创建此类包装器的方法 .asListLongs.asList 等。

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

A bit similar to the PHP behaviour is this:

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

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.

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

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

生死何惧 2024-10-25 14:11:17

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)

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

/** 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)
冰雪梦之恋 2024-10-25 14:11:17

我在网上经常看到这个问题,在我看来,许多享有盛誉的人都没有正确回答这些问题。所以我想在这里表达我自己的答案。

首先我们应该考虑有一个 arrayarraylist 之间的区别

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


答案非常简单。分 3 步即可完成。

  1. 将数组转换为数组列表
  2. 将元素添加到 arrayList
  3. 将新的 arrayList 转换回数组

这里是它的简单图片
输入图像描述这里

最后是代码:

第 1 步:

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

第 2 步:

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

            list.add(element);
            return list;
    }

第 3 步:

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

第 4 步< /强>

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

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.

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


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

  1. Convert array to an arraylist
  2. Add element to the arrayList
  3. Convert back the new arrayList to the array

Here is the simple picture of it
enter image description here

And finally here is the code:

Step 1:

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

Step 2:

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

            list.add(element);
            return list;
    }

Step 3:

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

Step 4

public String[] addNewItemToArray(String element,String [] array){
        List<String> list = convertArrayToList(array);
        list= addToList(element,list);
        return  convertListToArray(list);
}
绾颜 2024-10-25 14:11:17

您可以使用 ArrayList,然后使用 toArray() 方法。但根据您正在做什么,您甚至可能根本不需要数组。查看 Lists 是否更符合您的需求。

请参阅:Java 列表教程

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.

See: Java List Tutorial

她比我温柔 2024-10-25 14:11:17

您可能想为此使用 ArrayList - 对于动态大小的数组之类的结构。

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

沙与沫 2024-10-25 14:11:17

您可以使用 JAVA 中的集合框架动态地将元素添加到数组中。集合框架不适用于原始数据类型。

这个集合框架将在“java.util.*”包中提供

例如,如果您使用ArrayList,

请为其创建一个对象,然后添加元素数量(任何类型,如字符串,整数...等)

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

现在您添加了3个元素到数组。

如果您想

a.remove("suman");

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

a.add("Gurram");

那么数组大小会动态增加/减少。

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

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

For example if you use 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.

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

ま昔日黯然 2024-10-25 14:11:17

使用 ArrayList 或处理数组来自动增加数组大小。

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

海拔太高太耀眼 2024-10-25 14:11:17

记录您在原始数组中的位置

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;
    }
}

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;
    }
}
心房的律动 2024-10-25 14:11:17

这是在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);
    }

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.

    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);
    }
暮光沉寂 2024-10-25 14:11:17

在 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()));
        }
    }

}

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.

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()));
        }
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文