Regis
Regis

Reputation: 176

Creating a Generic array without using Arraylist

In order to complete one of my Java assignments, I have to do what seems like the impossible.

I have to create a method that takes in different stuff and plugs it into an array. We don't necessarily know what is being put into the array and thus the array must be able to accept Strings, Double, Integer, etc...

Of course, the obvious solution would be to use ArrayList<E> (i.e. a generic array). However, that's partly the complication of the problem. We cannot use an ArrayList, only a regular array. As far as I can find, when creating an array its intake value must be declared. Which leads me to believe that this assignment is impossible (yet I doubt the teacher would give me an impossible assignment).

Any suggestions?

Upvotes: 0

Views: 702

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Are you sure you need a generic array or an array that can hold anything?

If the former, then create a class that will act as wrapper of Object[] array and use a <T> generic for type cast when getting the elements of the array, which is similar to the implementation of ArrayList class. If the latter, use Object[] directly.

Upvotes: 0

Eran
Eran

Reputation: 393781

You can always use an array of Object - Object[].

Object[] objects = new Object[2];
objects[0] = "ABC";
objects[1] = Integer.valueOf("15");

Upvotes: 3

Related Questions