Java 如何将 List<String> 转换为 List<Object>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4288084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:25:08  来源:igfitidea点击:

How to Convert List<String> to List<Object>

javagenerics

提问by Alexs

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>. Is there a direct way in Java other then iterating over and converting element by element?

现有方法之一正在返回List<String>,我想将其转换为List<Object>. 除了逐个元素迭代和转换之外,Java 中还有直接的方法吗?

采纳答案by Erick Robertson

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 Collectioncan be passed as an argument to the constructor as long as its type extends the type of the ArrayList, as Stringextends Object. The constructor takes a Collection, but Listis a subinterface of Collection, so you can just use the List<String>.

AnyCollection可以作为参数传递给构造函数,只要它的类型扩展了 的类型ArrayList,如Stringextends Object。构造函数采用Collection, 但它List是 的子接口Collection,因此您只需使用List<String>.

回答by Riley Lark

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

回答by Martin Algesten

Any java collection is just a collection of objects be it string or other. 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.

任何 java 集合都只是对象的集合,无论是字符串还是其他。类型参数只是糖。根据情况,例如处理非常大的列表,您可能只想转换它 - 显然冒着在同一个列表中混合两种不同类型的对象的风险。

List<Object> objectList = (List)stringList;

And put a @SuppressWarning to get rid of nasties...

并放一个@SuppressWarning 来摆脱讨厌的东西......

回答by OscarRyz

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 addAllmethod, if the list of objects is an existing list.

作为替代方案addAll,如果对象列表是现有列表,您可以尝试该方法。

回答by qben

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
    }
}

回答by Mosayeb Masoumi

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

}

}

}