在java中向int []数组添加一个元素

时间:2013-04-09 10:38:41

标签: java arrays

想要向现有数组添加或附加元素

int[] series = {4,2};

现在我想用我发送的新值动态更新系列..

就像我发送3个更新系列int[] series = {4,2,3};

一样

再次,如果我发送4个更新系列为int[] series = {4,2,3,4};

再次,如果我发送1个更新系列为int[] series = {4,2,3,4,1};,那么

怎么做????

我在其他一些函数中每5分钟生成一个整数,并希望发送更新int[] series数组..

14 个答案:

答案 0 :(得分:66)

数组的长度在java中是不可变的。这意味着一旦创建了数组,就无法更改数组的大小。如果用2个元素初始化它,它的长度为2.但是你可以使用不同的集合。

List<Integer> myList = new ArrayList<Integer>();
myList.add(5);
myList.add(7);

使用包装器方法

public void addMember(Integer x) {
    myList.add(x);
};

答案 1 :(得分:47)

试试这个

public static void main(String[] args) {
    int[] series = {4,2};
    series = addElement(series, 3);
    series = addElement(series, 1);
}

static int[] addElement(int[] a, int e) {
    a  = Arrays.copyOf(a, a.length + 1);
    a[a.length - 1] = e;
    return a;
}

答案 2 :(得分:12)

如果每5分钟生成一个整数,最好使用集合。如果您的代码需要,您可以随时获取数组。

否则,将数组定义得足以在运行时处理所有值(尽管不是首选。)

答案 3 :(得分:7)

如果要添加索引,则需要创建新数组。

试试这个:

public static void main(String[] args) {
    int[] series = new int[0];
    int x = 5;


    series = addInt(series, x);

    //print out the array with commas as delimiters
    System.out.print("New series: ");
    for (int i = 0; i < series.length; i++){
        if (i == series.length - 1){
            System.out.println(series[i]);
        }
        else{
            System.out.print(series[i] + ", ");
        }
    }
}

//在这里,创建一个方法

public static int[] addInt(int [] series, int newInt){
    //create a new array with extra index
    int[] newSeries = new int[series.length + 1];

    //copy the integers from series to newSeries    
    for (int i = 0; i < series.length; i++){
        newSeries[i] = series[i];
    }
//add the new integer to the last index     
    newSeries[newSeries.length - 1] = newInt;



    return newSeries;

     }

答案 4 :(得分:5)

像其他人一样建议你最好使用收藏品。如果你出于某种原因必须坚持使用数组,那么Apache Commons ArrayUtils可能有所帮助:

int[] series = {4,2};
series = ArrayUtils.add(series, 3); // series is now {4,2,3}
series = ArrayUtils.add(series, 4); // series is now {4,2,3,4};

请注意,add方法创建一个新数组,复制给定数组并在末尾追加新元素,这可能会影响性能。

答案 5 :(得分:5)

你也可以试试这个。

public static int[] addOneIntToArray(int[] initialArray , int newValue) {

    int[] newArray = new int[initialArray.length + 1];
    for (int index = 0; index < initialArray.length; index++) {
        newArray[index] = initialArray[index];
    }

    newArray[newArray.length - 1] = newValue;
    return newArray;
}

答案 6 :(得分:4)

无法更改数组的大小。如果你想要一个更大的数组,你必须创建一个新数组。

但是,更好的解决方案是使用可以根据需要增长的(数组)列表。如果需要在应用程序中使用数组,方法ArrayList.toArray(T [] a)将返回一个数组。

答案 7 :(得分:2)

import java.util.Arrays;

public class NumberArray {     

    public static void main(String []args){
        int[] series = {4,2};
        int[] newSeries = putNumberInSeries(1,series);
        System.out.println(series==newSeries);//return false. you won't get the same int[] object. But functionality achieved.
    }
    private static int[] putNumberInSeries(int i, int[] series) {
        int[] localSeries = Arrays.copyOf(series, series.length+1);
        localSeries[series.length] = i;
        System.out.println(localSeries);
        return localSeries;
    }
}

答案 8 :(得分:2)

    public PropertiesPage()
    {
        InitializeComponent();

        List<PropertyGroup> properties = new List<PropertyGroup>();
        properties.Add(GetPropertyGroup("propertyGroup1"));
        properties.Add(GetPropertyGroup("propertyGroup2"));
        properties.Add(GetPropertyGroup("propertyGroup3"));

        propertyGrid.ItemsSource = properties;

    }

    private PropertyGroup GetPropertyGroup(string propertyGroupName)
    {
        return new CarrierConfig()
        {
            PropertyGroupName = propertyGroupName,
            Property1 = GetProperty1(propertyGroupName),
            Property2 = GetProperty2(propertyGroupName)
        };
    }

    public class PropertyGroup
    {
        public string PropertyGroupName { get; set; }
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    }

答案 9 :(得分:2)

...只能在JDK 1.5或更高版本中使用。如果您使用的是JDK 4或更低版本,请使用以下代码:&#39;

public static int[] addElement(int[] original, int newelement) {
    int[] nEw = new int[original.length + 1];
    System.arraycopy(original, 0, nEw, 0, original.length);
    nEw[original.length] = newelement;
}

否则(JDK 5或更高):

public static int[] addElement(int[] original, int... elements) { // This can add multiple elements at once; addElement(int[], int) will still work though.
    int[] nEw = new int[original.length + elements.length];
    System.arraycopy(original, 0, nEw, 0, original.length);
    System.arraycopy(elements, 0, nEw, original.length, elements.length);
    return nEw;
}

当然,正如上面提到的那样,您可以使用CollectionArrayList,这样您就可以使用.add()方法。

答案 10 :(得分:2)

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lRow As Long, i As Long
    Dim ObjChrt As Object
    Dim Chrt As Chart

    Set ws = Sheets("Sheet1")

    With ws
        '~~> Find the last row
        lRow = .Range("B" & .Rows.Count).End(xlUp).Row

        '~~> Loop through the values
        For i = 2 To lRow
            Set rng = .Range("B" & i & ":C" & i)

            '~~> Work with Chart Objects
            Set ObjChrt = .Shapes.AddChart
            Set Chrt = ObjChrt.Chart

            '~~> Assign relevant values
            With Chrt
                .SetSourceData Source:=ws.Range(rng.Address)
                .ChartType = xlLineMarkers
                .SeriesCollection(1).XValues = "='" & ws.Name & "'!$B$" & i & ":$C$" & i
                .SeriesCollection(1).Name = ws.Range("A" & i).Value
                .Location Where:=xlLocationAsNewSheet
            End With
        Next i
    End With

    Set ws = Nothing
    Set rng = Nothing
End Sub

答案 11 :(得分:2)

这对我有用:

int[] list = new int[maximum];
for (int i = 0; i < maximum; i++{
    list[i] = put_input_here;
}

这样,它简单而有效。

答案 12 :(得分:1)

类似于Evgeniy:

int[] series = {4,2};

  add_element(3);
  add_element(4);
  add_element(1);


public void add_element(int element){
  series = Arrays.copyOf(series, series.length +1);
  series[series.length - 1] = element;
}

答案 13 :(得分:0)

int [] oldArray = {1,2,3,4,5};

    //new value
    int newValue = 10;

    //define the new array
    int[] newArray = new int[oldArray.length + 1];

    //copy values into new array
    for(int i=0;i < oldArray.length;i++)
        newArray[i] = oldArray[i];
    //another solution is to use 
    //System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);

    //add new value to the new array
    newArray[newArray.length-1] = newValue;

    //copy the address to the old reference 
    //the old array values will be deleted by the Garbage Collector
    oldArray = newArray;