java - 更改 LinkedList 元素的位置
问题描述
我应该完成一个名为“substitute”的类,它可以在它们之间更改 LinkedList 的元素。我一直试图自己解决这个问题,但我对编程有点陌生,我无法找到答案,如果有人能帮助我,我将不胜感激。提前致谢。
我得到了无法更改的代码,只能写在括号内:
import java.util.Iterator;
import java.util.LinkedList;
public class Device implements Iterable<String>{
private static int numDevices=0; //device counter... static atribute
private String name;
private int id;
protected LinkedList<String> words;
public boolean substitute(String word1, String word2) {
//You can't use ListIterator<>
//You must use indexOf()...
//incomplete code that I'm not allowed to change ahead:
int position = this.words.indexOf(word1.toLowerCase());
return true;
}
我也应该通过这个 JUnit5 测试:
assertTrue(d1.substitute("amigo", "perla")); //returns true because the word amigo exists --> returns true
assertFalse(d1.substitute("amigo", "perla")); //the word amigo does not exist --> returns false
assertTrue(d1.substitute("estamos", "estas"));
assertTrue(d1.substitute("que", null)); //remove the word que
assertTrue(d1.substitute("tal", null)); //remove the word tal
解决方案
Java 中的 LinkedList 类有一些方法可以帮助你完成这个问题。使用在该位置找到的索引,您可以调用 remove() 或 set() 函数来帮助完成您的代码。
public boolean substitute(String word1, String word2) {
int position = this.words.indexOf(word1.toLowerCase());
if(position == -1) {
return false; // index of -1 means the word wasn't found in the list, return false
}
if(word2 == null) { // remove item if word2 is null as indicated by tests
words.remove(position);
} else {
words.set(position, word2); // set word2 at the position word1 was found at
}
return true;
}
推荐阅读
- java - 在 java 中使用广度优先搜索方法搜索 ZipEntry
- php - 如何访问 activeRecord 中模型的关系?
- android - 即使将值放入其中,内容值也被分配为 null
- css - 在 CSS Grid 中,为什么 1FR+9FR 在小屏幕尺寸中的行为与 10FR 不同?
- coq - 实数公理中的排除中间
- github-api - 如何启用 GitHub 预览功能,例如主题?
- javascript - 传单:使用 GeoJSON 掩码添加图像叠加层
- cakephp-3.0 - 如何在相关表中使用我的实体名称而不是 id
- javascript - String 和 Int 数组排序
- jquery - Json数据图表