0

Is it in Java possible to store classes...

Class1 class1 = new Class1();

...in Arrays/ArrayLists, somehow like this:

ArrayList<> classArray = new ArrayList();
classArray.add(class1);

Obviously this doesn't work, but how could it work?

3
  • 1
    Did you try google: java arrays and collections of objects? Commented Feb 13, 2021 at 19:08
  • Do you mean how to store objects of a certain class, or do you mean to ask how to store Class objects than represent a class? Commented Feb 13, 2021 at 21:48
  • no like an actual class, like class Fragment1, which displays a fragment. I want to store that whole Fragment class in a List Commented Feb 13, 2021 at 22:13

2 Answers 2

2

Of course you can. You just specify the type of objects you want to store when you create the array list:

ArrayList<Class1> classArray = ArrayList<Class1>();
classArray.add(class1);
Sign up to request clarification or add additional context in comments.

3 Comments

But when there are variable multiple Classes, and I don't know which gets in the ArrayList?
You either need to make it generic Java object ArrayList<Object> or you need to create a wrapper around it. You can check stackoverflow.com/questions/19602601/…
It is possible to use List<Object>, but I wouldn't do it.
1

If the class can only be Class1

ArrayList<Class1> list = new ArrayList<Class1>();

Above code won't allow any other class objects it can only store objects of type Class1

If you want to store any class object

ArrayList<Object> list = new ArrayList<Object>();

Object is a parent class of everything in java which is the reason why it can store object of any class

2 Comments

Let´s say I have that ArrayList with my class inside, which works fine. But now I want to change a fragment in a certain part of the application to another one, and the other one is the one in my ArrayList. How can I put that ArrayList in: manager.beginTransaction().replace(R.id.fragment_one, new //ArrayList with Class//).commit(); ?
manager.beginTransaction().replace(R.id.fragment_one, new ArrayList( listThatYouWantToPut)).commit(); And remember if you want to add type safety then use new ArrayList<Type>() else ArrayList()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.