0

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());

    }
}
4
  • What you are going to achieve by this? Seems you are doing something wrong Commented Nov 29, 2013 at 6:08
  • I'd like to limit adding objects by specifying objects. Commented Nov 29, 2013 at 6:10
  • For example as above, String, Interger, date. Commented Nov 29, 2013 at 6:10
  • You can't do like that, I mean, you can't make it add only those three object types. Commented Nov 29, 2013 at 6:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

I can't understand why generic of JAVA doesn't have this feature which can specify each objects.
Thank R.J. You make me know it's recommended way.
@user868754 - Glad to be of help to you! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.