S.J. Lim
S.J. Lim

Reputation: 3165

How to add multiple object in ArrayList which declared generic?

How to do that?

Following is tried code.


[Tried code]

package com.company;

import java.util.ArrayList;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        ArrayList<String, Integer, Date> myArray = new ArrayList<String, Integer, Date>();

        myArray.add("FIRST");
        myArray.add("SECOND");
        myArray.add("THIRD");

        // add multiple object
        myArray.add(new Integer(10));

        // add multiple object
        myArray.add(new Date());

    }
}

Upvotes: 0

Views: 134

Answers (2)

Rahul
Rahul

Reputation: 45070

The below line wouldn't even compile.

ArrayList<String, Integer, Date> myArray = new ArrayList<String, Integer, Date>();

What you're trying to achieve can be done using

ArrayList<Object> myArray = new ArrayList<>(); // Object type

but it is not at all a recommended option to do it. And while fetching the values back from the ArrayList, you need to handle the different types of objects manually, which is quite troublesome as well.

Therefore, it is always create ArrayList of the specific types you want to use.

ArrayList<String> myString = new ArrayList<>(); // For strings
ArrayList<Date> myDates = new ArrayList<>(); // For Date

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Yes, But not recommended.

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

Taking Object as a type , it accept all the types.

ArrayList<Object> myArray = new ArrayList<Object>();
myArray.add("FIRST");   //accepted
myArray.add(new Integer(10));  //accepted
myArray.add(new Date());  //accepted

So while getting also you need to take care of which Object you are getting back.

But, good recommendation is to take that individual list's for each type.

Upvotes: 1

Related Questions