Java - remove() function for ArrayList (I need help) [duplicate]Calling remove in foreach loop in JavaJava inner class and static nested classWhen to use LinkedList over ArrayList in Java?Why can't I define a static method in a Java interface?Type List vs type ArrayList in JavaConverting 'ArrayList<String> to 'String[]' in JavaRemoving whitespace from strings in JavaStatic Classes In JavaWhat is the difference between canonical name, simple name and class name in Java Class?Need Help Finding the intersection of two equations in JavaWhen use java regular-expression pattern.matcher(), source does not match regex.But, my hope result is ,source matches regex

SQL counting distinct over partition

Implement Own Vector Class in C++

How come the nude protesters were not arrested?

How to hide an urban landmark?

Longest bridge/tunnel that can be cycled over/through?

Thread Pool C++ Implementation

Winning Strategy for the Magician and his Apprentice

Is this use of the expression "long past" correct?

Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?

What setting controls moving the cursor on the command line?

Bent Peugeot Carbolite 103 Frame

How is John Wick 3 a 15 certificate?

Cascading Switches. Will it affect performance?

You have (3^2 + 2^3 + 2^2) Guesses Left. Figure out the Last one

Giant Steps - Coltrane and Slonimsky

Does Disney no longer produce hand-drawn cartoon films?

English word for "product of tinkering"

Electricity free spaceship

How to manually rewind film?

Is separation provided in class F airspace?

How can this tool find out registered domains from an IP?

Are there any important biographies of nobodies?

How to hide rifle during medieval town entrance inspection?

Is it a problem if <h4>, <h5> and <h6> are smaller than regular text?



Java - remove() function for ArrayList (I need help) [duplicate]


Calling remove in foreach loop in JavaJava inner class and static nested classWhen to use LinkedList over ArrayList in Java?Why can't I define a static method in a Java interface?Type List vs type ArrayList in JavaConverting 'ArrayList<String> to 'String[]' in JavaRemoving whitespace from strings in JavaStatic Classes In JavaWhat is the difference between canonical name, simple name and class name in Java Class?Need Help Finding the intersection of two equations in JavaWhen use java regular-expression pattern.matcher(), source does not match regex.But, my hope result is ,source matches regex






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-4
















This question already has an answer here:



  • Calling remove in foreach loop in Java [duplicate]

    11 answers



how can i remove an element that i had added before in the ArrayList<> I create it like that:



public static ArrayList<Product> P = new ArraList<Product>(); 


the method I am using:



public void removeProduct(Product p) 
P.remove(p); // this way, did not solve the problem



// I did the (added the method) and it works and everything are fine, I hope someone could help to get the answer and thanks :)



public void deleteProduct(String ID) 
System.out.println("Enter product id to delete: ");
ID = input.next();
for(Product m : s.P)
if(ID.equals(m.getID()))
s.P.remove(ID);

else
System.out.println("ID is not exist");





// and



public void removeProductToCart(Product p) 
viewShoppingCart();
System.out.println("Enter product id to remove it: ");
String ID = input.next();
for(Product r : s.P)
if(ID.equals(r.getID()))
s.P.remove(p);

else
System.out.println("ID is not exist");












share|improve this question















marked as duplicate by Carcigenicate, KevinO, GBlodgett, Mark Rotteveel, EdChum Mar 25 at 9:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 3





    What is the concrete problem. "I need help" doesn't tell us anything about the problem you're facing. What are you doing, what do you expect to happen, what happens instead? Be precise.

    – JB Nizet
    Mar 24 at 18:39











  • You write I did the (added the method) and it works and everything is fine. What are you need if is all fine?

    – Valentyn Hruzytskyi
    Mar 24 at 18:48











  • maybe an Exception is being thrown. If so, it would help to know about it (message, where, ...)

    – Carlos Heuberger
    Mar 24 at 18:59

















-4
















This question already has an answer here:



  • Calling remove in foreach loop in Java [duplicate]

    11 answers



how can i remove an element that i had added before in the ArrayList<> I create it like that:



public static ArrayList<Product> P = new ArraList<Product>(); 


the method I am using:



public void removeProduct(Product p) 
P.remove(p); // this way, did not solve the problem



// I did the (added the method) and it works and everything are fine, I hope someone could help to get the answer and thanks :)



public void deleteProduct(String ID) 
System.out.println("Enter product id to delete: ");
ID = input.next();
for(Product m : s.P)
if(ID.equals(m.getID()))
s.P.remove(ID);

else
System.out.println("ID is not exist");





// and



public void removeProductToCart(Product p) 
viewShoppingCart();
System.out.println("Enter product id to remove it: ");
String ID = input.next();
for(Product r : s.P)
if(ID.equals(r.getID()))
s.P.remove(p);

else
System.out.println("ID is not exist");












share|improve this question















marked as duplicate by Carcigenicate, KevinO, GBlodgett, Mark Rotteveel, EdChum Mar 25 at 9:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 3





    What is the concrete problem. "I need help" doesn't tell us anything about the problem you're facing. What are you doing, what do you expect to happen, what happens instead? Be precise.

    – JB Nizet
    Mar 24 at 18:39











  • You write I did the (added the method) and it works and everything is fine. What are you need if is all fine?

    – Valentyn Hruzytskyi
    Mar 24 at 18:48











  • maybe an Exception is being thrown. If so, it would help to know about it (message, where, ...)

    – Carlos Heuberger
    Mar 24 at 18:59













-4












-4








-4









This question already has an answer here:



  • Calling remove in foreach loop in Java [duplicate]

    11 answers



how can i remove an element that i had added before in the ArrayList<> I create it like that:



public static ArrayList<Product> P = new ArraList<Product>(); 


the method I am using:



public void removeProduct(Product p) 
P.remove(p); // this way, did not solve the problem



// I did the (added the method) and it works and everything are fine, I hope someone could help to get the answer and thanks :)



public void deleteProduct(String ID) 
System.out.println("Enter product id to delete: ");
ID = input.next();
for(Product m : s.P)
if(ID.equals(m.getID()))
s.P.remove(ID);

else
System.out.println("ID is not exist");





// and



public void removeProductToCart(Product p) 
viewShoppingCart();
System.out.println("Enter product id to remove it: ");
String ID = input.next();
for(Product r : s.P)
if(ID.equals(r.getID()))
s.P.remove(p);

else
System.out.println("ID is not exist");












share|improve this question

















This question already has an answer here:



  • Calling remove in foreach loop in Java [duplicate]

    11 answers



how can i remove an element that i had added before in the ArrayList<> I create it like that:



public static ArrayList<Product> P = new ArraList<Product>(); 


the method I am using:



public void removeProduct(Product p) 
P.remove(p); // this way, did not solve the problem



// I did the (added the method) and it works and everything are fine, I hope someone could help to get the answer and thanks :)



public void deleteProduct(String ID) 
System.out.println("Enter product id to delete: ");
ID = input.next();
for(Product m : s.P)
if(ID.equals(m.getID()))
s.P.remove(ID);

else
System.out.println("ID is not exist");





// and



public void removeProductToCart(Product p) 
viewShoppingCart();
System.out.println("Enter product id to remove it: ");
String ID = input.next();
for(Product r : s.P)
if(ID.equals(r.getID()))
s.P.remove(p);

else
System.out.println("ID is not exist");







This question already has an answer here:



  • Calling remove in foreach loop in Java [duplicate]

    11 answers







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 21:10









Valentyn Hruzytskyi

363317




363317










asked Mar 24 at 18:30









AhmedhussainAhmedhussain

12




12




marked as duplicate by Carcigenicate, KevinO, GBlodgett, Mark Rotteveel, EdChum Mar 25 at 9:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Carcigenicate, KevinO, GBlodgett, Mark Rotteveel, EdChum Mar 25 at 9:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 3





    What is the concrete problem. "I need help" doesn't tell us anything about the problem you're facing. What are you doing, what do you expect to happen, what happens instead? Be precise.

    – JB Nizet
    Mar 24 at 18:39











  • You write I did the (added the method) and it works and everything is fine. What are you need if is all fine?

    – Valentyn Hruzytskyi
    Mar 24 at 18:48











  • maybe an Exception is being thrown. If so, it would help to know about it (message, where, ...)

    – Carlos Heuberger
    Mar 24 at 18:59












  • 3





    What is the concrete problem. "I need help" doesn't tell us anything about the problem you're facing. What are you doing, what do you expect to happen, what happens instead? Be precise.

    – JB Nizet
    Mar 24 at 18:39











  • You write I did the (added the method) and it works and everything is fine. What are you need if is all fine?

    – Valentyn Hruzytskyi
    Mar 24 at 18:48











  • maybe an Exception is being thrown. If so, it would help to know about it (message, where, ...)

    – Carlos Heuberger
    Mar 24 at 18:59







3




3





What is the concrete problem. "I need help" doesn't tell us anything about the problem you're facing. What are you doing, what do you expect to happen, what happens instead? Be precise.

– JB Nizet
Mar 24 at 18:39





What is the concrete problem. "I need help" doesn't tell us anything about the problem you're facing. What are you doing, what do you expect to happen, what happens instead? Be precise.

– JB Nizet
Mar 24 at 18:39













You write I did the (added the method) and it works and everything is fine. What are you need if is all fine?

– Valentyn Hruzytskyi
Mar 24 at 18:48





You write I did the (added the method) and it works and everything is fine. What are you need if is all fine?

– Valentyn Hruzytskyi
Mar 24 at 18:48













maybe an Exception is being thrown. If so, it would help to know about it (message, where, ...)

– Carlos Heuberger
Mar 24 at 18:59





maybe an Exception is being thrown. If so, it would help to know about it (message, where, ...)

– Carlos Heuberger
Mar 24 at 18:59












2 Answers
2






active

oldest

votes


















1














2 problems:



  1. s.P is a list of products, not strings, so calling remove(String) doesn't work.

  2. Removing elements in a for-each loop will throw a ConcurrentModificationException


Possible solution:



public void removeProductToCart(Product p) 
viewShoppingCart();
System.out.println("Enter product id to remove it: ");
String ID = input.next();
Product toRemove = null;
for(Product r : s.P)
if(ID.equals(r.getID()))
toRemove = r;
break;


if(toRemove == null)
System.out.println("ID is not exist");

else
s.P.remove(toRemove);






This can be simplified if the passed argument is the product that needs to be removed.


The same logic can be applied to the first function:



public void deleteProduct(String ID) 
System.out.println("Enter product id to delete: ");
ID = input.next();
Product toRemove = null;
for(Product r : s.P)
if(ID.equals(r.getID()))
toRemove = r;
break;


if(toRemove == null)
System.out.println("ID is not exist");

else
s.P.remove(toRemove);




Note: The method arguments currently serve no purpose. Why not use them instead of looping to find the product?






share|improve this answer


















  • 1





    thanks you so much, you saved me, but there is another thing the shopping cart never deleted there, but thanks i can understand your way

    – Ahmedhussain
    Mar 24 at 19:29


















1














You need to use iterator, otherwise you will get java.util.ConcurrentModificationException. The exception is thrown, because you are doing 2 operations on the list: iteration and removal.



So, you need something like this:



for (Iterator<Book> it = s.P.listIterator(); it.hasNext(); ) 
Product r = it.next();
if(ID.equals(r.getID()))
it.remove(r);




Because, the root cause is performing 2 operations, there is another approach -
just create a copy of the list on each step of iteration:



for(Product m : new ArrayList<>(s.P)) 
if(ID.equals(m.getID()))
s.P.remove(m);




Note: Because of performance considerations (quadratic memory usage and linear removal on each step), I don't recommend the last approach. I give this example only to stress out the underlying reason why java.util.ConcurrentModificationException is thrown.






share|improve this answer































    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    2 problems:



    1. s.P is a list of products, not strings, so calling remove(String) doesn't work.

    2. Removing elements in a for-each loop will throw a ConcurrentModificationException


    Possible solution:



    public void removeProductToCart(Product p) 
    viewShoppingCart();
    System.out.println("Enter product id to remove it: ");
    String ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);






    This can be simplified if the passed argument is the product that needs to be removed.


    The same logic can be applied to the first function:



    public void deleteProduct(String ID) 
    System.out.println("Enter product id to delete: ");
    ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);




    Note: The method arguments currently serve no purpose. Why not use them instead of looping to find the product?






    share|improve this answer


















    • 1





      thanks you so much, you saved me, but there is another thing the shopping cart never deleted there, but thanks i can understand your way

      – Ahmedhussain
      Mar 24 at 19:29















    1














    2 problems:



    1. s.P is a list of products, not strings, so calling remove(String) doesn't work.

    2. Removing elements in a for-each loop will throw a ConcurrentModificationException


    Possible solution:



    public void removeProductToCart(Product p) 
    viewShoppingCart();
    System.out.println("Enter product id to remove it: ");
    String ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);






    This can be simplified if the passed argument is the product that needs to be removed.


    The same logic can be applied to the first function:



    public void deleteProduct(String ID) 
    System.out.println("Enter product id to delete: ");
    ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);




    Note: The method arguments currently serve no purpose. Why not use them instead of looping to find the product?






    share|improve this answer


















    • 1





      thanks you so much, you saved me, but there is another thing the shopping cart never deleted there, but thanks i can understand your way

      – Ahmedhussain
      Mar 24 at 19:29













    1












    1








    1







    2 problems:



    1. s.P is a list of products, not strings, so calling remove(String) doesn't work.

    2. Removing elements in a for-each loop will throw a ConcurrentModificationException


    Possible solution:



    public void removeProductToCart(Product p) 
    viewShoppingCart();
    System.out.println("Enter product id to remove it: ");
    String ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);






    This can be simplified if the passed argument is the product that needs to be removed.


    The same logic can be applied to the first function:



    public void deleteProduct(String ID) 
    System.out.println("Enter product id to delete: ");
    ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);




    Note: The method arguments currently serve no purpose. Why not use them instead of looping to find the product?






    share|improve this answer













    2 problems:



    1. s.P is a list of products, not strings, so calling remove(String) doesn't work.

    2. Removing elements in a for-each loop will throw a ConcurrentModificationException


    Possible solution:



    public void removeProductToCart(Product p) 
    viewShoppingCart();
    System.out.println("Enter product id to remove it: ");
    String ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);






    This can be simplified if the passed argument is the product that needs to be removed.


    The same logic can be applied to the first function:



    public void deleteProduct(String ID) 
    System.out.println("Enter product id to delete: ");
    ID = input.next();
    Product toRemove = null;
    for(Product r : s.P)
    if(ID.equals(r.getID()))
    toRemove = r;
    break;


    if(toRemove == null)
    System.out.println("ID is not exist");

    else
    s.P.remove(toRemove);




    Note: The method arguments currently serve no purpose. Why not use them instead of looping to find the product?







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 24 at 18:49









    Benjamin UrquhartBenjamin Urquhart

    1,304514




    1,304514







    • 1





      thanks you so much, you saved me, but there is another thing the shopping cart never deleted there, but thanks i can understand your way

      – Ahmedhussain
      Mar 24 at 19:29












    • 1





      thanks you so much, you saved me, but there is another thing the shopping cart never deleted there, but thanks i can understand your way

      – Ahmedhussain
      Mar 24 at 19:29







    1




    1





    thanks you so much, you saved me, but there is another thing the shopping cart never deleted there, but thanks i can understand your way

    – Ahmedhussain
    Mar 24 at 19:29





    thanks you so much, you saved me, but there is another thing the shopping cart never deleted there, but thanks i can understand your way

    – Ahmedhussain
    Mar 24 at 19:29













    1














    You need to use iterator, otherwise you will get java.util.ConcurrentModificationException. The exception is thrown, because you are doing 2 operations on the list: iteration and removal.



    So, you need something like this:



    for (Iterator<Book> it = s.P.listIterator(); it.hasNext(); ) 
    Product r = it.next();
    if(ID.equals(r.getID()))
    it.remove(r);




    Because, the root cause is performing 2 operations, there is another approach -
    just create a copy of the list on each step of iteration:



    for(Product m : new ArrayList<>(s.P)) 
    if(ID.equals(m.getID()))
    s.P.remove(m);




    Note: Because of performance considerations (quadratic memory usage and linear removal on each step), I don't recommend the last approach. I give this example only to stress out the underlying reason why java.util.ConcurrentModificationException is thrown.






    share|improve this answer





























      1














      You need to use iterator, otherwise you will get java.util.ConcurrentModificationException. The exception is thrown, because you are doing 2 operations on the list: iteration and removal.



      So, you need something like this:



      for (Iterator<Book> it = s.P.listIterator(); it.hasNext(); ) 
      Product r = it.next();
      if(ID.equals(r.getID()))
      it.remove(r);




      Because, the root cause is performing 2 operations, there is another approach -
      just create a copy of the list on each step of iteration:



      for(Product m : new ArrayList<>(s.P)) 
      if(ID.equals(m.getID()))
      s.P.remove(m);




      Note: Because of performance considerations (quadratic memory usage and linear removal on each step), I don't recommend the last approach. I give this example only to stress out the underlying reason why java.util.ConcurrentModificationException is thrown.






      share|improve this answer



























        1












        1








        1







        You need to use iterator, otherwise you will get java.util.ConcurrentModificationException. The exception is thrown, because you are doing 2 operations on the list: iteration and removal.



        So, you need something like this:



        for (Iterator<Book> it = s.P.listIterator(); it.hasNext(); ) 
        Product r = it.next();
        if(ID.equals(r.getID()))
        it.remove(r);




        Because, the root cause is performing 2 operations, there is another approach -
        just create a copy of the list on each step of iteration:



        for(Product m : new ArrayList<>(s.P)) 
        if(ID.equals(m.getID()))
        s.P.remove(m);




        Note: Because of performance considerations (quadratic memory usage and linear removal on each step), I don't recommend the last approach. I give this example only to stress out the underlying reason why java.util.ConcurrentModificationException is thrown.






        share|improve this answer















        You need to use iterator, otherwise you will get java.util.ConcurrentModificationException. The exception is thrown, because you are doing 2 operations on the list: iteration and removal.



        So, you need something like this:



        for (Iterator<Book> it = s.P.listIterator(); it.hasNext(); ) 
        Product r = it.next();
        if(ID.equals(r.getID()))
        it.remove(r);




        Because, the root cause is performing 2 operations, there is another approach -
        just create a copy of the list on each step of iteration:



        for(Product m : new ArrayList<>(s.P)) 
        if(ID.equals(m.getID()))
        s.P.remove(m);




        Note: Because of performance considerations (quadratic memory usage and linear removal on each step), I don't recommend the last approach. I give this example only to stress out the underlying reason why java.util.ConcurrentModificationException is thrown.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 24 at 18:54

























        answered Mar 24 at 18:47









        ZgurskyiZgurskyi

        1,404179




        1,404179













            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현