How can I create an array without using an inline array?

I am new to programming and am learning Java. I was wondering, without using the built-in array system, how would you program a class that represents an array? I tried it and found I didn't know how to do it. It shouldn't be generic to types, maybe someone can explain how to program an int array?

Edit: Lots of helpful feedback. If it is not possible to program the same array type as the default, how does the language do it? Also, I don't really like the syntax, just the functionality. And I understand the use of other similar collections like linked lists, but they will not be exactly the same.

+3


source to share


2 answers


It is possible to create a class that is almost identical to the functionality by creating a linked list (as alfasin mentioned), but you cannot emulate all the functionality and performance characteristics of an array. Namely, you can never simulate the syntax array[index]

or access time of a constant array (O (1) in algorithmic terms).



The Java Virtual Machine does this by accessing raw memory. Actually it is not possible to do this in Java (technically it is possible in Java with sun.mics.unsafe, but this is HIGHLY discouraged), but possible with build / source commands and extension through certain languages ​​like C, C ++ and etc.

+4


source


You can create a class and implement some of the interfaces associated with the array, namely List

, Iterable

. It will be something like this:

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

      

If you are new to Java, you may not know what it is. It was called generics. If you don't want to play with generics, you can simply do:



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

      

If you are using eclipse you can simply click "add unimplemented methods" in the quick fixes. List

there are many tutorials for details on how to implement . I am just giving you a general guide.

+1


source







All Articles