Lorena Lago Vallejo
Lorena Lago Vallejo

Reputation: 31

Can I create an ArrayList of different types in Java

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?

Upvotes: 2

Views: 215

Answers (5)

René Link
René Link

Reputation: 51343

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.

Upvotes: 6

user1983983
user1983983

Reputation: 4841

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.

Upvotes: 1

Chowdappa
Chowdappa

Reputation: 1620

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
  }
}

Upvotes: 1

X-Pippes
X-Pippes

Reputation: 1170

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

try this. Use an Object class of java

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

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

Upvotes: 0

Related Questions