I need to create an ArrayList and fill it with BigDecimals and a Date elements, how do I do?
Should I create a new Class with all the types I need in the ArrayList and then use it as the type?
I need to create an ArrayList and fill it with BigDecimals and a Date elements, how do I do?
Should I create a new Class with all the types I need in the ArrayList and then use it as the type?
It would be interesting to know what you try to achieve.
If the BigDecimals and Dates do have a logical relation, e.g. like a the amount of a bank transaction and it's placed date, than you should think about introducing a new class that brings both together (hopefully named BankTransaction). You can than put objects of this class in the List.
If the BigDecimals and Dates have nothing to do with each other why do you want to store them in the same list? In this case you will confuse other developers since they must take a look at the code that interpretes the List and they can not guess what it means because of the list's type.
Nevertheless you can use the List<Object> approach, but this would not be self-explanantory code like List<BankTransaction> for example.
Use code like below:
List<Object> list2 = new ArrayList<Object>();
list2.add(new BigDecimal(3242));
list2.add(new Date());
for (Object object : list2) {
if(object instanceof Date) {
// your logic on date
} else if (object instanceof BigDecimal) {
// your logic on BigDecimal
}
}
Just use a List<Object>
List<Object> list = new ArrayList<Object>();
Although this way works properly and fits your question, you should definitly check your requirements and if you really need to add Dates and BigDecimals to the same List, as this is not a good practice.
new ArrayList<>() in our example code now.All classes in Java inherit from the base Object class, so you can just create an ArrayList that accepts Object instances, and put whatever you like in it:
List<Object> list = new ArrayList<Object>();
list.add(new Date()); // adds a Date instance
list.add(new BigDecimal()); // adds a BigDecimal