Johnny Mccrum
Johnny Mccrum

Reputation: 57

How to create and fill an Unlimited Array

Earlier last week I was in an android/Java class, and our lecturer likes to throw little challenges at us every now and then, just as fun little programs for us to think about.

The topic I'm studying is OOP and OOD in c# and Java environments, so this really doesn't have any huge leverage on my actual final project, and I'd like to stress this was an optional task set for fun.

The Task was asking for the programmer to:

Create a program that could hold an "unlimited" array of integers (based on how many the user required) and find the max value in the array.

The issue wasn't the max method (easy), or the variables in the array (basic), but the array itself. we weren't allowed to use linked lists, it had to be an "Unlimited" 1D array that could take user input.

I've been playing around with the array for a while now, was going to make a circular array at first but that still doesn't solve many of the issues, and I can't really work out how to solve the problem in a way that this could be ported over and used in c#

any ideas as to how this could be achieved?

Upvotes: 0

Views: 2585

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

If you can't use only LinkedList you can use any other implementation of java.util.List.

If you can't use at all java.util.List you can use an array with enough values as you need and use a pointer to the last value. Something like this

 public class MyArray {
     private int[] myArray = new int[10000];
     private int index = -1;

     public void add(int obj) {
        index++;
        myArray[index] = obj;
     }

     public Integer removeLast() {
         if (index >= 0) {
             return myArray[index--];
         }
         return null;
     }

     public Integer get(int i) {
         if (i >= 0 && i < index) {
             return myArray[i];
         }
         return null;
     }
 }

Note. This is very similar to the internal representation of ArrayList. Take a tour of source of ArrayList to know more, the biggest difference is that this implentation is blocked to a maximum of 10000 ints, instead the ArrayList can grows if necessary, but I think that the grows implementation is outside the scope of your exercise.

Upvotes: 1

Related Questions