java - 从 String 数组到 ArrayList 转换的性能相关

标签 java

我正在将一个空 String 数组(我可以从中间件获取)转换为 List 。

对于转换过程,我使用了 Arrays.asList (请参阅下面的代码),它抛出 java.lang.UnsupportedOperationException 。

public class Ramddd {
    public static void main(String args[]) {
        String[] words = null;
        if (words == null) {
            words = new String[0];
        }
        List<String> newWatchlist = Arrays.asList(words);
        List<String> other = new ArrayList<String>();
        other.add("ddd");
        newWatchlist.addAll(other);
    }

}



Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(Unknown Source)
    at java.util.AbstractList.add(Unknown Source)
    at java.util.AbstractCollection.addAll(Unknown Source)
    at Ramddd.main(Ramddd.java:18)

如果我使用,我不会收到此错误

List<String> mylist = new ArrayList<String>();
        for (int i = 0; i < words.length; i++) {
            mylist.add(words[i]);
        }

这形成了一个正确的List,并且任何诸如addALLremoveALL之类的操作似乎都不错,但不想采用这种for循环方法,因为这可能会导致性能下降。 请让我知道将 String 数组转换为 ArrayList 的最佳且安全的方法是什么。

最佳答案

以下怎么样:

public class Ramddd {
    public static void main(String args[]) {
        String[] words = getWords();
        if (words == null) {
            words = new String[0];
        }
        List<String> other = new ArrayList<String>(Arrays.asList(words));
        other.add("ddd");
    }
}

就性能而言,我不认为这是值得担心的事情,除非您有一个非常巨大的字符串数组。

关于java - 从 String 数组到 ArrayList 转换的性能相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14740486/

相关文章:

java - Apache MQ 扫描消息

java - JPA 与 Hibernate 4.x,@ElementCollection,主键

java - 在 Debian 服务器上使用来自 Tomcat 的 JDBC

java - 无法使用Java初始化Spark上下文

java - 如何使用 Android 中的加速度计值计算特定轴的旋转速率

java - 在 Java 6 中使用继承的 stdin/stdout/stderr 启动进程

java - 如何在java中获取特定日期UTC值

java - 创建新的maven项目指南

java - 如何从 xml 生成 Edifact 消息?

java - SonarQube 不使用 IntelliJ 和 Maven 分析主要的 java 代码