swinters
swinters

Reputation: 347

creating a Collection<object> from object

I have an object: p I need: Collection allThePs

I tried:

Collection<object> allThePs = (Collection<object>) p;

as well as:

Collection<object> allThePs;
allThePs.add(p);

From what I've found, I'm not sure what I'm trying to do is possible because a collection is abstract. How do I get this as a collection?

Upvotes: 2

Views: 84

Answers (2)

isurujay
isurujay

Reputation: 1436

You can do like this.

    Object o = "Something";
    Collection<Object> allThePs = new ArrayList<>();
    allThePs.add(o);

You cant use just a Collection class to store data. You need to have one of its implementations. Eg: ArrayList

Upvotes: 1

dotvav
dotvav

Reputation: 2848

You need to initialize the collection with an actual implementation of Collection. For example:

Collection<Object> allThePs = new ArraylList<>();
allThePs.add(p);

Upvotes: 2

Related Questions