有一个数组列表,并想删除使用 .equals 进行比较时传递的元素。移除此对象并在空白处移动元素。如果没有元素,我将返回 false。
public boolean remove(E obj) {
return false;
}
好吧,如果您想返回布尔值,请执行以下操作:
public boolean remove(E obj) {
ArrayList<Object> myList = new ArrayList();
for(Object object: myList){
if(object.equals(obj){
return true;
}}
return false;
}
如果要返回没有目标的列表,请执行以下操作:
public ArrayList<Object> remove(E obj) {
ArrayList<Object> myList = new ArrayList();
ArrayList<Object> answerList = new ArrayList();
for(Object object: myList){
if(object.equals(obj){
continue;
}
answerList.add(object);
}
return answerList;
}
当您从 ArrayList 中删除某些内容时,其余元素将向左移动以填充。由于您的 List 可能未实现某些方法,因此在调用之前将其放入 ArrayList 很重要。
List<Integer> list = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
// Then you can just remove the object. It will return true if deleted or
// false if not. Note, you need to cast the value to type Object if it's an
// Integer, otherwise it will assume it is an index.
System.out.println(list.remove((Object) 120)); // prints false
System.out.println(list); // prints [10, 20, 30, 40, 50]
System.out.println(list.remove((Object) 40)); // prints true
System.out.println(list); // prints [10 20, 30, 50]
希望这可以帮助:
public class Application {
public static void main(String[] args) {
ListWrapper<String> wrapper = new ListWrapper<>(new ArrayList<>(Arrays.asList("1", "2", "3")));
wrapper.print();
System.out.println("REMOVE:" + wrapper.remove("2"));
wrapper.print();
}
public static class ListWrapper<T> {
private final ArrayList<T> list;
public ListWrapper(ArrayList<T> list) {
this.list = list;
}
public boolean remove(T obj) {
boolean removed = list.remove(obj);
list.trimToSize();
return removed;
}
public void print() {
System.out.println("LIST: " + list);
}
}
}