1

So, I was writing a Java program and made a method create that accepted Object datatype variable. Here is the brief look

class FILO
{
   ArrayList listFILO;
   public void create(Object input)
   {
      Class<? extends Object> type=input.getClass();
      if(type.isArray())
      {
        /*Problem starts here. I want to create an array with same datatype as
         input but I can't get my head around it.*/
       }
         //...
    }
}
4
  • I think generics might solve your problem, but maybe you are after something different here? Commented Jan 7, 2021 at 17:27
  • 1
    When posting here, learn to use code formatting. Another user fixed some of your post this time. You should still fix the indenting. Commented Jan 7, 2021 at 21:49
  • @BasilBourque (yep it made my eyes feel bad) -- l'd let him polish the format Commented Jan 7, 2021 at 21:54
  • Sorry, I would remember this. Commented Jan 8, 2021 at 0:45

1 Answer 1

1

You could use reflection, using java.lang.reflect.Array.

Array.newInstance( input.getClass(), length );

But trying to use reflection like this is usually a bad idea. You want to require the user to enter the type you are asking for, and then check that the user has entered the correct type.

Sign up to request clarification or add additional context in comments.

1 Comment

This program may cause a lot of errors, and I had to create it as I needed a variable which followed First In Last Out. So I decided to create a class which would I then use to create a custom variable with the functions I need. If anyone has any other suggestions how to deal, then please do tell me. And sorry for the code, as I didn't had my computer and wrote the question on my phone

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.