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

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript