Yellvis
Yellvis

Reputation: 161

Adding data to arrays Java

I had an idea for a way to bypass the hard limit on spaces for a normal array in Java. Would this work?

public class Array{
  private int[] group;

  public void addNums(int[] nums) {
    int[] list = new int[group.length + nums.length];
    for (int a = 0; a < group.length; a++)
      list[a] = group[a];
    for (int a = group.length; a < nums.length; a++)
      list[a] = nums[a - group.length];
    group = list;
  }
}

Upvotes: 0

Views: 83

Answers (3)

djm.im
djm.im

Reputation: 3323

If you have to use int[] instead List<Integer>, you can use System.arraycopy() method.

public void addNums(int[] nums) {
    int[] newGroup = new int[this.group.length + nums.length];

    // copy elements from group array to newGroup array
    System.arraycopy(group, 0, newGroup, 0, group.length);

    // copy elements from nums array to newGroup array
    System.arraycopy(nums, 0, newGroup, this.group.length, nums.length);

    this.group = newGroup;
}

Upvotes: 0

Luke Garrigan
Luke Garrigan

Reputation: 5011

First of all, I commend you for trying to create your own ArrayList as you said you are a beginner to java.

You are really close there's just a small issue with your second for loop:

public void addNums(int[] nums) {
    int[] list = new int[group.length + nums.length];
    for (int a = 0; a < group.length; a++)
        list[a] = group[a];

    for (int a = group.length; a < list.length; a++)
        list[a] = nums[a -group.length];
    group = list;
}

You want it to loop to the end of your new listrather than nums because we want to use a to specify the position in the array the element is going.

Also, this might be a little offtopic but your solution there doesn't seem to be anywhere within your Array class to be able to specify what is within the group[]. So consider adding some getters and setters for testing:

public class Array {

    private int[] group;

    public int[] getGroup() {
        return group;
    }

    public void setGroup(int[] group) {

        this.group = group;
    }

And then when you are testing your addNums() method you could do something like this:

public static void main(String[] args) throws IOException {

    Array m = new Array();

    int[] startArray = {1,2,3,4,5};
    m.setGroup(startArray);

    int[] endArray = {6,7,8,9,10,11,12};
    m.addNums(endArray);

    System.out.println(Arrays.toString(m.getGroup()));
}

Upvotes: 1

Ralf Kleberhoff
Ralf Kleberhoff

Reputation: 7290

Your approach will work, but you shouldn't re-invent the wheel. ArrayList. addAll() does this for you (one difference, there is no ArrayList<int>, only ArrayList<Integer>, but you'll hardly notice the difference).

So, I'd recommend to use ArrayList or Vector or some other List implementation.

Upvotes: 0

Related Questions