如何解决如何将字符串从一个索引交换到另一个索引?
到目前为止,这是我的代码,我不确定如何获取列表 [fish,chips,sauce,plate]
的索引并将 chips
放在索引 plate
处。
class Names{
ArrayList<String> list;
public Names()
{
list = new ArrayList<String>();
}
/** precondition: p and q represent indexes of existing elements in the list array.
* postcondition: the elements,represented by p and q,have swapped locations.
*/
public void swapNames(int p,int q){
temp = p;
p = q;
q = temp;
}
}
解决方法
建议
请阅读数组和集合操作的基础知识
假设
输入不会包含重复项
方法
- 使用 indexOf 获取元素的索引
- 删除两个元素(先删除较大的索引,然后删除较小的索引)
- 首先选择较低的索引值并插入替换元素
- 然后插入更高的索引值(确保检查 size() 如果是最后一个元素)
解决方案
final String first = "chips"
final String second = "plate"
final int index1 = list.indexOf(first);
final int index2 = list.indexOf(second);
if (index1 < index2) {
list.remove(index2);
list.remove(index1);
list.add(index1,second)
if (index2 == list.size()) {
list.add(first);
} else {
list.insert(index2,first);
}
} else {
// do the reverse
}
,
如果 p
和 q
是给定数组列表中的有效索引,则可以使用 ArrayList
的方法 get(int i)
和 set(int i,E obj)
有效地交换元素:
public void swapNames(int p,int q) {
String temp = list.get(p);
list.set(p,list.get(q));
list.set(q,temp);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。