john
john

Reputation: 41

how to create an array without using built in array?

I'm new to programming and am learning java. I was wondering, without using the built in array system, how would you program a class representing an array? I tried and found I didn't know how. It doesn't have to be generic for types, just maybe could somebody explain how to program an int array?

Edit: lots of helpful feedback. If it's not possible to program the same kind of array as is default, how does the language do it? Also, I don't really care about the syntax, just the functionality. And I understand using other similar collections like linked lists, but they wouldn't fully be the same.

Upvotes: 4

Views: 837

Answers (2)

NitrogenReaction
NitrogenReaction

Reputation: 336

It's possible to make a class that functions nearly identically by creating a linked list (As mentioned by alfasin), but you cannot emulate all of an array's functionality and performance characteristics. Namely, you can never simulate the array[index] syntax nor an array's constant access time (O(1) in algorithmic terms).

The Java Virtual Machine does it by accessing raw memory. It is not really possible to do that in Java (It is technically possible in Java by using sun.mics.unsafe, but that is HIGHLY discouraged), but is possible with assembly/raw instructions and, by extension, via certain languages such as C, C++, etc.

Upvotes: 4

Sweeper
Sweeper

Reputation: 271135

You can create a class and implement some array-related interfaces, namely List, Iterable. This will be something like this:

public class MyArray<T> implements List<T> {
    //your implementation here
}

If you're new to Java, you might not know what those are. It's called generics. If you don't want to play with generics, you can just do:

public class MyArray implements List<Object> {
        //your implementation here
}

If you are using eclipse, you can just click on the "add unimplemented methods" in the quick fixes. for details of how to implement List, there are lots of tutorials out there. I am just giving you a general guide.

Upvotes: 1

Related Questions