0

I have built a static method that adds an element to an array (which has a fixed size). You don't have to look at the entire method, it just creates a new array with a greater length and adds an element at the end of it, then returns the new array.

static int[] add(int[] oldArray, int value){
    int n = oldArray.length;
    int[] newArray = new int[n+1];
    for(int i=0; i<n; i++){
        newArray[i]=oldArray[i];
    }
    newArray[n] = value;
    return newArray;
}

The method is supposed to be used as follows

int[] a = {2, 5};
a = add(a, 7);

Now the array a has three elements instead of two, namely 2, 5 and 7. The problem is, this is still a little messy. Is there a way to implement the method as non-static (in a "predefined array class" or something? I'm not too sure how to express it better) in such a way that it would work as follows instead?

int[] a = {2, 5};
a.add(7);

I'm trying to achieve this without using ArrayLists and NestedLists.

  • 3
    No. You can't add methods to arrays. To achieve something like `manyElements.add(newElement)` in a way similar to array we use lists like ArrayList. They also store elements at indexes and unlike arrays don't have fixed size. So your code would be like `list.add(element)`. – Pshemo Jan 10 '23 at 16:50
  • 1
    _"I'm trying to achieve this without using ArrayLists and NestedLists"_ - is this an academic question or do you have actual requirements to work without lists? – Marvin Jan 10 '23 at 16:52
  • 1
    @Marvin we haven't been taught Lists in school and I don't want to get penalized for using them (yes, it happens), but at the same time I don't want my code to be too messy. I was hoping to be able to "create" my own ArrayList by only using what we have already been taught. – Dark Rebellion Jan 10 '23 at 17:34
  • The Java [Arrays API](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Arrays.html) does have methods that can resize arrays. If an array is made larger, zeroes are added. See [`public static int[] copyOf​(int[] original, int newLength)`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Arrays.html#copyOf(int%5B%5D,int)), for example. – Old Dog Programmer Jan 10 '23 at 17:52

4 Answers4

2

You cannot add a method to "the array class", same for all predefined classes, the only solution for other predefined classes is to inherit them and add the methods you want, but, this cannot be done for arrays as it has not a specific predefined class, it can be defined as a container object that holds a fixed number of values of a single type (Arrays).

The alternative solutions for what you want:

  • Use Lists (ArrayList for example), as described in the comments.

  • concatenate the array original content with the new element, for this solution, you can use ArrayUtils.addAll(T[] array1, T... array2) or System.arraycopy like the following sample (convert the new element to an array before)

    String[] both = ArrayUtils.addAll(first, second);
    
  • Create a class to wrap the array (adding the array as a variable in this class), and create addElement method containing something like the following:

     int[] newArray = new int[length + 1];
     for (int i = 0; i < length; i++)
         newArray[i] = this.array[i];
     newArray[length] = element;
     length ++;
     array = newArray;
    
1

Is there a way to implement the method as non-static (in a "predefined array class" or something? I'm not too sure how to express it better) in such a way that it would work as follows instead?

No, there is not. You must use something like List, or optionally write your own interface that wraps an array (it cannot itself be an array).

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Could you elaborate on the "interface that wraps an array" part, if it's not too much work? "Creating" my own ArrayList in some way is exactly what I was trying to achieve. – Dark Rebellion Jan 10 '23 at 17:37
  • `interface MyIntList { void add(int value); ...probably other methods here... } class MyIntListImpl implements MyIntList { private int[] internalArray; ...your implementation here... }` – Louis Wasserman Jan 10 '23 at 17:48
  • @DarkRebellion see the answers at https://stackoverflow.com/questions/889160/what-is-a-wrapper-class – Old Dog Programmer Jan 10 '23 at 17:49
1

What you're asking for are called "extension methods" in C#, but as others have already answered, they don't exist in Java. However, Project Lombok (which is full of very useful features that most professional Java developers should be aware of and use), implements them with a simple annotation.

Here's an example:

package so_75073262;

public class ArrayExtensions {

    public static int[] add(int[] oldArray, int value) {
        int n = oldArray.length;
        int[] newArray = new int[n + 1];

        for (int i = 0; i < n; i++) {
            newArray[i] = oldArray[i];
        }
        newArray[n] = value;
        return newArray;
    }
}
package so_75073262;

import lombok.experimental.ExtensionMethod;

@ExtensionMethod(ArrayExtensions.class)
public class Usage {

    public static void main(String[] args) {
        int[] original = {2,5};
        int[] modified = original.add(7);

        System.out.println(modified[0]);
        System.out.println(modified[1]);
        System.out.println(modified[2]);
    }
}

Lombok is a form of "magic" and probably would get "interesting" responses from some course instructors; I'm not sure I'd recommend using this in an introductory Java class. But it's still useful to know about; it's a powerful tool to have in your toolbox, and can help keep code tidy and uncluttered.

E-Riz
  • 31,431
  • 9
  • 97
  • 134
-1

I think you should take a reference of How ArrayList is getting implemented and how its size increases dynamically. Since it uses Array internally for the implementation, you might get some suggestions from there.

  • I got the idea exactly from seeing how ArrayLists get implemented, that is by creating a new array with greater length and copying all the items from the original array. But I am stuck at making it look like "array.add(5)" rather than "array = add(array, 5)" – Dark Rebellion Jan 10 '23 at 18:01