1
$\begingroup$

TL;DR I'm looking for a replacement for the primitive array data type in Java that works better with generic data types.

Background: I'm teaching A level CS in the UK (age 16-18) and we're using Java as our primary language. The students are already familiar with python.

To teach some data types, we're coding them in Java. The specification regards a fixed-length, single type array as a primitive data type so to code, say, a queue we build a class with an array to hold the data in the queue and then add methods accordingly. The array data type in Java matches that of the specification nicely, so this works quite well.

Partly for my own interest (I have experience of other languages, but haven't done much Java before) but also because I like to have an example for the students of "what if you wanted to do a bit more", then I wanted to extend my queue class to have a generic type. But this seems quite complicated since the primitive array type doesn't work well with generic types (this is well explored over on StackOverflow, see https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java for example) - unlike in other similar languages, such as C#.

So my question is as to whether there is a replacement for the array data type in Java which is sufficiently similar to array that it doesn't change the learning experience (so, single data type and fixed length) but which can take a generic type.

$\endgroup$

1 Answer 1

2
$\begingroup$

You probably want an ArrayList. They can be resized, however. Python has a similar thing.

You should become familiar with the oracle docs of which the above link is a part. They are quite informative.

An older type is the Vector, but it has been largely replaced by ArrayList.

$\endgroup$
2
  • $\begingroup$ Thank you. I suspected that ArrayList would be the choice, after all if implementing a "better" array then removing the fixed length condition would be an obvious one to do. Thanks also for the pointer to the oracle docs - I hadn't figured out the "oracle" of java docs as yet via random internet searches. $\endgroup$ Nov 20, 2023 at 22:00
  • 2
    $\begingroup$ When Sun (inventer of Java) left the scene, Oracle bought out the company. Many employees left for Oracle also. $\endgroup$
    – Buffy
    Nov 20, 2023 at 22:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.