简体   繁体   English

如何转换列表<String>列出<Object>

[英]How to Convert List<String> to List<Object>

I want to convert List<String> to List<Object> .我想将List<String>转换为List<Object>

One of the existing methods is returning List<String> and I want to convert it to List<Object> .现有方法之一是返回List<String> ,我想将其转换为List<Object> Is there a direct way in Java other then iterating over and converting element by element?除了逐个元素迭代和转换之外,Java 中还有直接的方法吗?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> .List<String>作为参数传递给 new ArrayList<Object>的构造函数。

List<Object> objectList = new ArrayList<Object>(stringList);

Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .任何Collection都可以作为参数传递给构造函数,只要它的类型扩展ArrayList的类型,就像String扩展Object The constructor takes a Collection , but List is a subinterface of Collection , so you can just use the List<String> .构造函数采用Collection ,但ListCollection的子接口,因此您可以只使用List<String>

Any java collection is just a collection of objects be it string or other.任何 java 集合都只是对象的集合,无论是字符串还是其他。 The type argument is just sugar.类型参数只是糖。 Depending on situation, such as dealing with very large lists, you may just want to convert it - obviously risking mixing two different types of objects in the same list.根据情况,例如处理非常大的列表,您可能只想转换它 - 显然冒着在同一个列表中混合两种不同类型的对象的风险。

List<Object> objectList = (List)stringList;

And put a @SuppressWarning to get rid of nasties...并放一个@SuppressWarning 来摆脱讨厌的东西......

Personally, while both of the currently top rated answers are right in a way, I do not think any of them solves the problem in an elegant, reusable way, especially if you have to do this very often.就个人而言,虽然目前评价最高的两个答案在某种程度上都是正确的,但我认为它们中的任何一个都无法以优雅、可重用的方式解决问题,尤其是在您必须经常这样做的情况下。

Suppose you have some old legacy code / dependency that you cannot change in any way (so that it would at least accept List<? extends Object> as @ReverendGonzo suggested in his comment . Suppose also, that you need to talk to this legacy module a lot.假设您有一些旧的遗留代码/依赖项,您无法以任何方式更改(这样它至少会接受List<? extends Object>正如@ReverendGonzo 在他的评论中所建议的那样。还假设您需要与这个遗留模块交谈很多。

I do not think either casting / copying all the time would be bearable on the long run.我认为从长远来看,无论是铸造还是复制都是可以忍受的。 It makes your code either vulnerable to insidious bugs and hard to follow or slightly (or drastically) inefficient and hard-to-read.它使您的代码容易受到潜在错误的影响并且难以遵循,或者略微(或严重)低效且难以阅读。

To have readable and efficient production code, it is better to encapsulate the dirty part in a separate module which deals with the otherwise harmless but ugly cast.为了拥有可读和高效的生产代码,最好将脏部分封装在一个单独的模块中,该模块处理其他无害但丑陋的演员。

class ProductionCode {
    public void doJob() {
        List<String> strings = Arrays.asList("pear", "apple", "peach");
        StringMagicUtils.dealWithStrings(strings);
    }
}

class StringMagicUtils {
    @SuppressWarnings("unchecked")
    public static void dealWithStrings(List<String> strings) {
        ExternalStringMagic.dealWithStringsAsObjects((List) strings);
    }
}

// Legacy - cannot edit this wonderful code below ˇˇ
class ExternalStringMagic {
    public static void dealWithStringsAsObjects(List<Object> stringsAsObjects) {
        // deal with them as they please
    }
}

This is pretty inefficient, but at least you don't have to write a lot of code~这样效率很低,但至少不用写很多代码了~

List<String> stringList = new ArrayList<String>();
List<Object> objectList = Arrays.asList(stringList.toArray());

If you are willing to convert to an unmodifiable List<Object> , you can simply wrap your list with Collections.unmodifiableList .如果您愿意转换为不可修改的List<Object> ,您可以简单地用Collections.unmodifiableList包装您的列表。 This works because this static method has a proper wildcard type ? extends T这是有效的,因为这个静态方法有一个正确的通配符类型? extends T ? extends T for the element type of the wrapped list (where T is the type of the result list).为包装列表的元素类型? extends T (其中T是结果列表的类型)。

Note that, in most cases, creating an unmodifiable view is what you should do, otherwise objects of different types (other than String ) may be added in the original list (which should only hold String s).请注意,在大多数情况下,您应该做的是创建一个不可修改的视图,否则可能会在原始列表中添加不同类型的对象(除了String )(应该只包含String )。

List<Object> ofObjects = new ArrayList<Object>(ofStrings);

as in:如:

import java.util.*;
class C { 
  public static void main( String[] args ) { 
     List<String> s = new ArrayList<String>();
     s.add("S");
     List<Object> o = new ArrayList<Object>(s);
     o.add( new Object() );
     System.out.println(  o );

  }
}

As an alternative you can try the addAll method, if the list of objects is an existing list.作为替代方案,如果对象列表是现有列表,您可以尝试addAll方法。

model.class模型.class

public class Model {公共类模型{

private List<String> stringList = new ArrayList<>();

public List<String> getStringList() {
    return stringList;
}

public void setStringList(List<String> stringList) {
    this.stringList = stringList;
}

} }

MainActivity主要活动

public class MainActivity extends AppCompatActivity {公共类 MainActivity 扩展 AppCompatActivity {

Model model = new Model();
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner=findViewById(R.id.spinner);

    List<String> itemList = new ArrayList<String>();
    itemList.add("item1");
    itemList.add("item2");
    itemList.add("item3");


   model.setStringList(itemList);


    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, model.getStringList());
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(dataAdapter);

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM