【问题标题】:Convert ArrayList to LinkedList将 ArrayList 转换为 LinkedList
【发布时间】:2015-10-07 04:46:21
【问题描述】:

如果我想将此实现从 ArrayList 更改为 LinkedList 我只需要更改

ArrayList<Character> characters = new ArrayList<Character>();

LinkedList<Character> characters = new List<Character>();

或者我该怎么做?

ArrayList<Character> characters = new ArrayList<Character>();
try {
    while((str = bufferedReader.readLine()) != null){
        char [] characterArray = str.toCharArray();

        for (int i = 0; i <  characterArray.length; i++){

            characters.add(characterArray[i]);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
char [] patternArray = phrase.toCharArray();
ArrayList<Character> pattern = new ArrayList<Character>();
for (int i = 0; i <  patternArray.length; i++) {

    pattern.add(patternArray[i]);
}

【问题讨论】:

  • List list = new LinkedList 而不是 ArrayList

标签: java arraylist linked-list


【解决方案1】:

这段代码很好地说明了为什么对接口进行编程是一件好事。你继续使用这种声明模式:

ArrayList<Character> characters = new ArrayList<Character>();

如果您希望将characters 设为链表,则必须在两个地方进行更改。如果你在声明中使用了接口名称,像这样

List<Character> characters = new ArrayList<Character>();

您的其余代码将继续工作,但您可以进行一次更改以转换为LinkedList

List<Character> characters = new LinkedList<Character>();

pattern 变量的声明也是如此。

太慢了,占用内存太多

当然可以!长链表占用更多的内存,因此将它们用于逐个字符的表示是不切实际的。通常,只有在处理少量短字符串时,才可以将字符串转换为字符列表。在其他情况下,如果需要可变性,最好使用 String 对象或 StringBuilder 对象。

【讨论】:

  • 我试过这个兄弟,但它需要很长时间才能运行。太慢了,占用内存太多
  • @bond007 - 这可能意味着你应该坚持使用ArrayList,而不是改用LinkedList
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多