1

How could I add an element to an array? I could easily simplify my code if I could add an element to an array. My code is shown below.

public int[] intersection(int[] nums1, int[] nums2) {
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    int[] nums2_1 = nums2;
    int[] nums2_2 = nums2;
    int length = 0;
    int number =0;
    if ((nums1.length != 0) && (nums2.length != 0)) {
        for (int i = 0; i < nums1.length; i++) {
            boolean valid = true;
            if ((i != 0) && (nums1[i-1] == nums1[i])) {
                valid = false;
            }
            if (binarySearch(nums2_1, nums1[i], 0, nums2.length-1) && valid) {
                length++;
            }
        }
    }
    int[] nums3 = new int[length];
    if ((nums1.length != 0) && (nums2.length != 0)) {
        for (int i = 0; i < nums1.length; i++) {
            boolean valid = true;
            if ((i != 0) && (nums1[i-1] == nums1[i])) {
               valid = false;
            }
            if (binarySearch(nums2_2, nums1[i], 0, nums2.length-1) && valid) {
                nums3[number] = nums1[i];
                number++;
            }
        }
    }
    return nums3;
}
Brandon Chen
  • 77
  • 1
  • 11

3 Answers3

2

Arrays have a fixed length in Java. If you need to dynamically size your collections of ints, you should consider using one of the implementions of List instead. Then you can add elements to it with the .add() method.

It would look something like this:

List<Integer> nums3 = new ArrayList<Integer>();

and then instead of nums3[number] and keeping track of the number variable, just use

nums3.add(nums1[i]);
Brandon Dockery
  • 185
  • 1
  • 8
1

Arrays should be used when you know the definite size of the Input. If you do not know the definite size, then its advisable to use the collections framework, based on the usage.

pradz_stack
  • 176
  • 1
  • 11
0

Arrays has fixed size. Easy way to add elements to array is to create another array whose size is old array size + 1. Now add the last element.

Otherwise use ArrayList

sunny
  • 158
  • 1
  • 2
  • 13