Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
It depends on what you need to do with the objects in the array. –  Radiodef Oct 5 '14 at 4:58

2 Answers 2

up vote 3 down vote accepted

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

Object[] objects = new Object[2];
objects[0] = "ABC";
objects[1] = Integer.valueOf("15");
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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