2012-02-05 76 views
5

我在转换时遇到困难。我不知道是否有语法错误,或者这是不可能的。从ArrayList转换为集合

我需要转换from--

private static final List<Contact> CONTACTS = Arrays.asList(
     new Contact("text1", "name1"), 
     new Contact("text2", "name2"), 
     new Contact("text3", "name3")); 

中场休息

Collection c = new ArrayList(Arrays.asList(--?--)) 

- ? - - >(我不明白这里会发生什么)

通过这样做,我打算避免UnsupportedOperationException。 任何帮助表示感谢,谢谢!

嘿谢谢大家,我明白了! 这worked--
解决方案:

List<? extends Contact> col = new ArrayList<Contact>(CONTACTS); 
+1

1)这与GWT有什么关系? 2)你可以添加你想要做的'集合',什么触发UnsupportedOperationException? – Grilse 2012-02-05 03:41:42

+0

当你调用列表中的remove()时,你是否得到'UnsupportedOperationException'? – LanguagesNamedAfterCofee 2012-02-05 05:27:39

+0

我无法申请CONTACT.remove(index);对ArrayList进行操作。 – Prince 2012-02-05 05:31:23

回答

1

我正在更新它作为我正在寻找的答案。谢谢大家的回复!

List<? extends Contact> col = new ArrayList<Contact>(CONTACTS); 
9
public interface List 
extends Collection 

You don't need to do anything。还是有一些你需要的操作,ArrayList不支持?

+0

我无法申请CONTACT.remove(index);对ArrayList进行操作。 – Prince 2012-02-05 05:32:14

+1

@Prince这是因为Collection接口没有Collection.remove(index)方法,只有一个Collection.remove(Object o)方法。见http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html – Yuushi 2012-02-05 10:06:34

1

这样做的工作:

private static final Collection<String> c = new ArrayList<String>(
               Arrays.asList("a", "b", "c")); 

因此我建议是这样的:

private static final Collection<Contact> = new ArrayList<Contact>(
         Arrays.asList(new Contact("text1", "name1") 
            new Contact("text2", "name2"))); 
+0

谢谢,但这不会对我工作bcoz我一直需要更新以前更新的联系人列表中的联系人,这将每次给我原始列表。 – Prince 2012-02-05 14:28:06

4

你不必做任何事情来执行转换,这个工程:

List<Contact> CONTACTS = new ArrayList<String>(); 
// fill CONTACTS 
Collection<Contact> c = CONTACTS; 

CollectionList的超级接口,如果一个对象im它也将执行。