Conversion from ArrayList to Collection
Solution 1
I am updating it as an answer I was looking for. Thank you all for your responses!
List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);
Solution 2
public interface List
extends Collection
You don't need to do anything. Or is there some particular operation you need that the ArrayList
doesn't support?
Solution 3
You don't have to do anything to perform that conversion, this works:
List<Contact> CONTACTS = new ArrayList<String>();
// fill CONTACTS
Collection<Contact> c = CONTACTS;
Collection
is the super-interface of List
, if an object implements List
it will also implement Collection
.
Solution 4
Doing this works:
private static final Collection<String> c = new ArrayList<String>(
Arrays.asList("a", "b", "c"));
Thus I'd suggest something like:
private static final Collection<Contact> = new ArrayList<Contact>(
Arrays.asList(new Contact("text1", "name1")
new Contact("text2", "name2")));
Prince
Updated on August 06, 2022Comments
-
Prince over 1 year
I am having difficulty in this conversion. I don't know if there is a syntax error or this is not even possible.
I need to convert from--
private static final List<Contact> CONTACTS = Arrays.asList( new Contact("text1", "name1"), new Contact("text2", "name2"), new Contact("text3", "name3"));
To--
Collection c = new ArrayList(Arrays.asList(--?--))
--?-- --> (I don't understand what comes here)
By doing this, I intend to avoid UnsupportedOperationException. Any help appreciated, thanks!
Hey thank you all, i got it! This worked--
Solution:List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);
-
Prince about 12 yearsI cannot apply CONTACT.remove(index); operation on the ArrayList.
-
Yuushi about 12 years@Prince That's because the Collection interface doesn't have a Collection.remove(index) method, only a Collection.remove(Object o) method. See docs.oracle.com/javase/6/docs/api/java/util/Collection.html
-
Prince about 12 yearsThanks but this will not work for me bcoz i consistently need to update contact from previously updated contact list and this would give me the original list everytime.