class EX6
{
private int value;
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some numbers (all on one line, separated by spaces):");
String line = input.nextLine();
String[] numbers = line.split(" +");
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i=0; i<numbers.length; i++)
a.add(new Integer(numbers[i]));
System.out.println("The numbers are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
EX6 ex = new EX6();
ex.value = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
System.out.println(removeNumber(a,ex));
}
public static <T> ArrayList<T> removeNumber(ArrayList<T> a, EX6 e)
// Adds n after every occurrence of m in a, constructively.
{
ArrayList<T> b = new ArrayList<T>();
for(int i=0; i<a.size(); i++)
{
if(a.get(i) == e)
{
a.remove(i);
}
}
return a;
如果我在[5,12 ,4, 16,4]
中输入值ArrayList
,并在4
中输入JOptionPane
,我想删除所有4
'列表中的。
我如何将ex.value传递给方法removeNumber()???
答案 0 :(得分:0)
您可以重复使用ArrayList.remove(Object)
ArrayList al = ...;
int elementToRemove = ...;
boolean found;
do {
found = al.remove((Integer)elementToRemove);
} while (found);
答案 1 :(得分:0)
你可以尝试这个,只需通过它定义迭代器和迭代器,找到你要删除的匹配元素,然后从迭代器中删除。它将删除Arraylist中的元素,因为Iterator指的是Arraylist。
public static <T> ArrayList<T> removeNumber(ArrayList<T> a, EX6 e)
{
Iterator i = a.iterator();
while(i.hasNext())
{
if(i.next().equals((Integer)e.value))
{
i.remove();
}
}
return a;
}