Home > database >  How to determine which objects are stored in an arraylist?
How to determine which objects are stored in an arraylist?

Time:09-22

If I have 3 class called CPU,GPU,RAM and I stored these classes into an arraylist ArrayList<Object> stock = new ArrayList<>() what method can you use to return which class is stored in a certain index. Eg

stock = new ArrayList<>;
stock.add(new CPU());
stock.add(new GPU());
//method to determine which class is in index 0 
System.out.println(method);
Output: class packageName.CPU

CodePudding user response:

use the stock.get(index).getClass() as pointed out by markspace this is horrible practice, better to have a base interface.

CodePudding user response:

Only the first element

You can simply get the element 0, then the class and finally the name of it.

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

class CPU{};
class GPU{};

stock.add(new CPU());
stock.add(new GPU());

System.out.println(stock.get(0).getClass().getName());

and the output is what you want:

com.example.example.model.CPU

All the elements

If you need all the classes just add a foreach in the process:

stock.forEach(i -> {
    System.out.println(i.getClass().getName());
});

com.example.example.model.CPU

com.example.example.model.GPU

  • Related