[英]How to move the selected item to move to the top of the list
List<String> strings; // contains "foo", "bar", "baz", "xyz"
and if given an input "baz"
the function re-arrange(String input) should return the strings 如果给出输入
"baz"
则函数重新排列(String输入)应该返回字符串
"baz", "foo", "bar", "xyz"
and if given an input "bar"
the function re-arrange(String input) should return the strings 如果给出一个输入
"bar"
,函数重新排列(String输入)应该返回字符串
"bar", "foo", "baz", "xyz"
First, remove the item and then add the item again at position 1. 首先,删除该项目,然后在位置1再次添加该项目。
List<String> strings;
List<String> rearrange(String input) {
strings.remove(input);
strings.add(0,input);
return strings;
}
public static <T> List<T> rearrange(List<T> items, T input) {
int index = items.indexOf(input);
List<T> copy;
if (index >= 0) {
copy = new ArrayList<T>(items.size());
copy.add(items.get(index));
copy.addAll(items.subList(0, index));
copy.addAll(items.subList(index + 1, items.size()));
} else {
return items;
}
return copy;
}
public static <T> void setTopItem(List<T> t, int position){
t.add(0, t.remove(position));
}
To move the original item to the top of the original list: 要将原始项目移动到原始列表的顶部:
public static <T> void rearrange(List<T> items, T input){
int i = items.indexOf(input);
if(i>=0){
items.add(0, items.remove(i));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.