从java中的另一个类中删除arraylist中的指定对象

时间:2018-05-22 10:37:50

标签: java arraylist

我想根据用户输入从另一个类中删除arraylist中的指定数据 所以当用户输入Rice时,数据与Rice'在它将被删除 这是到目前为止的代码

数据存储在名为RegularMenu的子类中的ArrayList rm中。

ArrayList<RegularMenu> rm = new ArrayList<RegularMenu>();

Quiz1(){
    int input;
        do{
            System.out.println("1. Add Regular Menu");
            System.out.println("2. Add Special Menu");
            System.out.println("3. Show All Menu");
            System.out.println("4. Delete Regular Menu");
            System.out.println("5. Delete Special Menu");
            System.out.println("6. Exit" + "\n"); 

            System.out.print("Choice [1-6] ");
            Scanner s = new Scanner(System.in);
            input = s.nextInt();

            if (input == 1 ){

                String code, name;
                int price;

                System.out.println("Add Regular Menu");
                System.out.print("Input Menu Code [R...]: ");
                s.nextLine();
                code = s.nextLine();

                System.out.print("Input Menu Name [5-20]: ");
                name = s.nextLine();

                System.out.print("Input Menu Price [10000-130000]: ");
                price = s.nextInt();

                rm.add(new RegularMenu(code, name, price));
            }

            else if (input == 2){

            }

            else if (input == 3){

            }

            else if (input == 4){


                System.out.println("Input menu code you want to delete");
                String a = s.nextLine();

                for(int i=0;i<rm.size();i++){
                    if(a == rm.get(i).getCode()){
                        String code = rm.get(i).getCode();
                        a = code;
                        rm.remove(a);
                    }

                }

            }

            else if (input == 5){

            }
        }while(input != 6);
}

我可以添加数据,但是当尝试删除它时,发生了错误。 如果我不够清楚,请告诉我。

5 个答案:

答案 0 :(得分:2)

问题是您使用的是List.remove(Object)错误而不是List.remove(int)

List.remove(对象)

boolean remove(Object o)

  

从此列表中删除第一次出现的指定元素(如果存在)(可选操作)。 [...]更正式地,删除具有最低索引i的元素,使(o==null ? get(i)==null : o.equals(get(i))) [...]

尝试使用RegularMenu实例移除String将无效,因为String实例无法与RegularMenu进行比较,因此永远不会当量。 (它将使用String.equals(RegularMenu)方法查找要删除的实例的位置。

如果您想使用List.remove(Object),请传递实例本身:

rm.remove(rm.get(i));

注意:

  1. 这将仅删除第一次出现,因此如果您有两个“等效”实例,则只会删除第一个实例。
  2. List.remove(Object)将搜索实例传递的索引,使用Object.equals按索引删除。但在您的情况下,您已使用if(a == rm.get(i).getCode())完成了工作(错误地看到“字符串比较”),
  3. List.remove(int)的

    E remove(int index)

      

    删除此列表中指定位置的元素(可选操作)。将任何后续元素向左移位(从索引中减去一个)[...]

    由于您知道索引,因此可以使用rm.remove(i)List.remove(int))删除当前索引处的值。

    小心那样的索引,列表的右边部分左移。有关详细信息,请参阅Lajos Arpad's answer

    迭代

    ArrayList中删除项目的另一个解决方案是使用迭代器。您获得Iterator并迭代其中的每个项目。然后,如果匹配,则拨打Iterator.remove以正确删除该项目。如果您只想删除一个项目,您甚至可以停止循环

    示例数据:

    List<String> datas = new ArrayList<>();
    datas.add("foo");
    datas.add("bar");
    datas.add("bar");
    datas.add("foo");
    datas.add("bar");
    datas.add("bar");
    

    代码:

    Iterator<String> it = datas.iterator();
    String s;
    while(it.hasNext()){
        s = it.next();
        if("foo".equals(s)){
            it.remove();
        }
    }
    
    System.out.println(datas);
    
      

    [酒吧,酒吧,酒吧,酒吧]

    我精确地使用ArrayList因为某些Collection没有为remove提供Iterator的方法Exception

    谓词 - removeIf

    自Java 8以来,Collection.removeIf存在并允许您更快地解决方案(使用相同的示例数据):

    final String a = "foo";
    datas.removeIf(s -> a.equals(s));
    
    System.out.println(datas);
    
      

    [酒吧,酒吧,酒吧,酒吧]

    如果传递的RegularMenuPredicate,它将迭代并检查其中true的每个实例,如果是,则该项将被删除。

    字符串比较

    另请注意比较"foo".equals(s)而不是"foo" == s How do I compare strings in Java?

    中的更多信息

答案 1 :(得分:1)

您可以通过索引从列表中删除元素

for(int i=rm.size()-1; i>=0; i--) {
    // you are deleting elements from the list while iterating,
    // thus it is better to iterate backwards (rm.size()..0):

    if(a.trim().equals(rm.get(i).getCode().trim())) {
        rm.remove(i);
    }
}

注意:当您删除索引i下的元素时,右侧(i+1, ...)的所有元素都将向左移动一个位置。

因此,当从左到右迭代并删除元素时,你会搞乱索引 另一方面,当你从右向左迭代并删除位置i的某些东西时,所有向右的元素仍然会向左移动一个位置,但这对你没关系,因为你会不要迭代它们。

aaaaBcccc    ->  aaaacccc
^   ^            ^   ^ 
0.. i            0.. i

答案 2 :(得分:1)

您可以使用循环迭代数组列表并删除所有匹配项:

for (int i = 0; i < yourArrayList.size(); i ++) {
    if(a.equals(rm.get(i).getCode())){
        yourArrayList.remove(i--);
    }
}

您的错误是您尝试remove使用aArrayList removeremove期望int代表i要删除的索引。在我的代码通知中,我在删除之后递减remove以便能够进行private String fileName = "deutsch.txt"; File file = new File(getClass().getClassLoader().getResource(fileName).getFile()); private RemoteAdapter() { this.spellchecker = SpellcheckerFactory.createSpellchecker(file); } 后续匹配。

答案 3 :(得分:0)

for(int i=0;i<rm.size();i++) {
    if(a.trim().equals(rm.get(i).getCode())) {
        rm.remove(i);
        break;
    }
 }

在列表中,您可以使用索引删除元素。

答案 4 :(得分:-1)

查找以下代码:

               for(RegularMenu regularMenu:rm){
                     if(a.equalsIgnoreCase(regularMenu.getCode())){
                           rm.remove(regularMenu);
                           break;
                        }