如果我想将此实现从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]);
}
最佳答案
这段代码很好地说明了为什么对接口(interface)进行编程是一件好事。你继续使用这个声明模式:
ArrayList<Character> characters = new ArrayList<Character>();
如果您希望将 characters
设为链表,则必须在两个地方进行更改。如果您使用接口(interface)名称作为声明,就像这样
List<Character> characters = new ArrayList<Character>();
你的代码的其余部分将继续工作,但你将能够进行一次更改以转换为 LinkedList
:
List<Character> characters = new LinkedList<Character>();
pattern
变量的声明也是如此。
It is too slow and uses too much memory
当然可以!长链接列表占用更多内存,因此将它们用于逐字符表示是不切实际的。通常,字符串到字符列表的转换仅在处理少量短字符串时才实用。在其他情况下,如果您需要可变性,您最好使用 String
对象或 StringBuilder
对象。
关于java - 将 ArrayList 转换为 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31476230/