• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Removing elements from an ArrayList

 
Ranch Foreman
Posts: 906
8
  • Number of slices to send:
    Optional 'thank-you' note:
My contract ended a few weeks ago.  I got rid of a bunch of tasks and have been learning Java again.  

I'm creating an ArrayList in the main() method.  It is in Class Elementy.  I'll want to have less code in main so I'll move the contents to a different class later on.  

The ArrayList has mostly Ford brand automobiles.   I pass the array to Class FordOnly.

In FordOnly I am attempting to remove elements that are not other brands of automobiles.

I mention lambda's in one of the comments but,  I won't try that until I get this code working this way.

I'm getting an error message in the console.   I don't know what is wrong.  Here is the code and also the error messages:



"C:\Program Files\Java\jdk-17\bin\java.exe" -Didea.launcher.port=61071 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\study\Java study\JCL_Update\out\production\JCL_Update;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMainV2 aRaise.Elementy
[Mustang, Volkswagen, Bronco, Chrysler, Taurus, Skylark, Explorer, Skylark, Expedition, Chrysler, Maverick, Volkswagen, Ranger]
Mustang
Volkswagen
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
at aRaise.FordOnly.processArray(FordOnly.java:22)
at aRaise.Elementy.main(Elementy.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

Process finished with exit code 1



 
Saloon Keeper
Posts: 10779
86
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
You can't remove items from a Collection that you are looping through. Instead, make a new collection with the elements you want and when you're done replace the original collection with the new one.

Alternatively, some collections support the use of an Iterator which has a remove()  method that will remove the current element.

 
Marshal
Posts: 79392
377
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:

kevin Abel wrote:. . . The ArrayList has mostly Ford brand automobiles.   I pass the array to Class FordOnly. . . .

That sentene has two things in that confuse me.
  • 1 You ae calling an array list an array. A List isn't an array and an array isn't a list.
  • 2: The name of the class: FordOnly. I am not convinced that is a good form of inheritance. I am happy to see class Taxi extends Car, but not happy with things like class Ford extends Car. The Ford only bit wouild apply better to the name of a method than a class, but even that is iffy design; it would be better to pass information about what to remove and not suggest you are finding a particular manufacturer at all.
  • You can have a List<CarType> and use it for all types of car and a second one containing only Ford types. Note I didn't say to have a List<String>, for reasons explained here by Winston Gutkowski. It is better to create a CarType class, and maybe CarManufacturer too. Then you can iterate your List, and this is where a Stream would work well, apply a Predicate testing whether the manufacturer is Ford, and collect the elements into a new List.
    I am afraid I don't like your multiple ifs; not only is that repeated code, but also it means the code has to “know” which elements are to be removed from the List. It would be better to use a single if, but as Carey says, you will still have the concurrent modification problem because a for‑each loop always uses an Iterator in the background.
    Try the removeIf() method on your List.
    Find out how to use an Iterator in a for loop and what advantage that might have over the customary use of a while.
     
    Carey Brown
    Saloon Keeper
    Posts: 10779
    86
    • Number of slices to send:
      Optional 'thank-you' note:

     
    Campbell Ritchie
    Marshal
    Posts: 79392
    377
    • Number of slices to send:
      Optional 'thank-you' note:
    The following loop will run nicely for an array list, as you will find here, but can run horribly slowly on a linked list. I hope you know the advantage the for loop has over the usual way of writing a while loop. I hope you have also seen the advantage of using removeIf(), which Carey showed you.
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Carey,

    The iterator looks like it can be useful.  

    Best,

    Kevin
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Campbell,

    I almost always (probably more always)  agree with you.   Your comments, suggestions and ideas help me a lot.  They have a ton of useful parts.  I get concerned that you provide me with so much improvement that I cannot remember it all.  Please continue how you answer me.  It is perfect.  I use Java intermittently mostly as a hobby and I remember many things from everyone but, its so much data that I forget things. I try not to ask the same things over and over. Sometimes I don't even recognize that I am in the same trap.    

    Anyway...Back to code:

    . . . The ArrayList has mostly Ford brand automobiles.   I pass the array to Class FordOnly. . . .


    That sentene has two things in that confuse me.
    1 You ae calling an array list an array. A List isn't an array and an array isn't a list.


    >>  It would make more sense if I wrote:
    The ArrayList has mostly Ford brand automobiles.   I pass the arrayList to Class FordOnly. . . .

    2: The name of the class: FordOnly. I am not convinced that is a good form of inheritance. I am happy to see class Taxi extends Car, but not happy with things like class Ford extends Car. The Ford only bit wouild apply better to the name of a method than a class, but even that is iffy design; it would be better to pass information about what to remove and not suggest you are finding a particular manufacturer at all.
    You can have a List<CarType> and use it for all types of car and a second one containing only Ford types. Note I didn't say to have a List<String>, for reasons explained here by Winston Gutkowski. It is better to create a CarType class, and maybe CarManufacturer too. Then you can iterate your List, and this is where a Stream would work well, apply a Predicate testing whether the manufacturer is Ford, and collect the elements into a new List.

    >>I would like to do what you said here(see the next paragraph please) .  I can't visualize how I would do this.
    It is better to create a CarType class, and maybe CarManufacturer too. Then you can iterate your List, and this is where a Stream would work well, apply a Predicate testing whether the manufacturer is Ford, and collect the elements into a new List.


    I  am afraid I don't like your multiple ifs; not only is that repeated code, but also it means the code has to “know” which elements are to be removed from the List. It would be better to use a single if, but as Carey says, you will still have the concurrent modification problem because a for‑each loop always uses an Iterator in the background.

    >> I don't like the multiple ifs either.   I was curious if there is something like an "in" for Java.  A method that determines if any strings listed in the method match the current one.

    Try the removeIf() method on your List.
    Find out how to use an Iterator in a for loop and what advantage that might have over the customary use of a while.  
    >> This sounds like what Carey wrote about.  

    Best,

    Kevin
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Carey,

    I appreciate the example with the lambda.  I think I should figure this out without labdas first.

    Kevin
     
    Marshal
    Posts: 4525
    572
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:... I was curious if there is something like an "in" for Java.  A method that determines if any strings listed in the method match the current one.


    You could create a Set of models that you want to exclude, and then remove all the models in your list which are contained in the Set.

     
    Carey Brown
    Saloon Keeper
    Posts: 10779
    86
    • Number of slices to send:
      Optional 'thank-you' note:
    This is where I'd start. Using a Car class (or  in my case "Kar") with a make and model. Then provide an isMake() method. This method can then be used in any of the techniques mentioned above.
     
    Campbell Ritchie
    Marshal
    Posts: 79392
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:. .. Your comments, suggestions and ideas help me a lot.  They have a ton of useful parts.  I get concerned that you provide me with so much improveme . . .

    Thank you

    The ArrayList has mostly Ford brand automobiles.   I pass the arrayList to Class FordOnly. . . .

    That's better Better still, I think,would be to say “list” but that is only my opinion.

    2: The name of the class: FordOnly. . . .

    I would use a utility class called ListUtilities with a (static) removeContents method taking the two Lists as parameters. But when you go through the List interface and find t which methods it already has, you will find methods like removeAll(), removeIf(), and contains(), which do what you want already, so you might not need that utility lass at all.

    Campbell itchie wrote:Find out how to use an Iterator in a for loop and what advantage that might have over the customary use of a while.  

    >> This sounds like what Carey wrote about.  

    Best,

    Kevin

    No, I think nobody has mentioned this particular point. The for loop restricts the scope of the Iterator variable so there is no chance of a concurrent modification situation later on in the same method. If you need to restrict the scope with a while, you need an additional pair of {}Of course, if your method is short, as it should be, there won't be anything after the loop to cause any problems.
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Ron,
    Set.of looks like a useful class.  I see that it is an interface.
    Appreciated.
    Kevin
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Campbell,

    I like the Winston Gutkowski link about Strings.

    I'm writing this from memory from the article:

    Seat [5] [12] = Seat .reserved.()

    i need to go back to the article to get the exact line of code.  

    I know how to use an array with [] [] but I can't see how to made a class that takes in the two bracket pieces of data.

    Kevin



     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    I went back to the article and got the line of code:

    seats[x][y].reserve();
     
    Campbell Ritchie
    Marshal
    Posts: 79392
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:Campbell,

    I like the Winston Gutkowski link about Strings.

    Yes, he's canny, isn't he.

    . . . Seat [5] [12] = Seat .reserved.() . . .

    I am glad you corrected that, because it makes reserve() look like a static method.
     
    Campbell Ritchie
    Marshal
    Posts: 79392
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    A few minutes ago, I wrote:. . . Yes, he's canny, isn't he. . . . .

    Where I live, being canny is a good thing.
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Hello Carey and Ranchers,

    I am back from a Virgin Voyage Cruise.  I'm not on a project and I'm returning to my hobbies of learning Mandarin Chinese, Playing the trumpet, dancing and exploring Java.

    I created a new package and broke up Carey's code into Classes. I realize that his code is the concept and not degugged or exact.     Intellij is showing red underlines all over the place.

    I will make comments and add questions.  

    I want to see how to use the Kar and ListCarDemo Classes.  

    There is an enum.   I know it is an enumerator and must be a collection.   I don't know if it is part of a class or if there is a way to make an enum in a package.

    I plan to work on this tomorrow or soon.

    Best to everyone,

    Kevin



     
    Carey Brown
    Saloon Keeper
    Posts: 10779
    86
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:There is an enum.   I know it is an enumerator and must be a collection.   I don't know if it is part of a class or if there is a way to make an enum in a package.


    An enum is NOT a collection. It is a kind of class with a specific structure, behavior, and members. Also, any part of your code that makes use of an enum will be enclosed in code by the compiler to take advantage of those features.

    An enum is a fundamental building block in Java and you should know and understand its basics. I suggest googling "java enum tutorial".
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Corey,

    I am reading about enum here:

    https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

    It starts explaining the enum like this:

    An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

    Because they are constants, the names of an enum type's fields are in uppercase letters.

    In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:


    public enum Day {
       SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
       THURSDAY, FRIDAY, SATURDAY
    }

    What I don't know is where the enum goes in the code.   Does it go in a class where other data structures and primitives are declared?

    I also looked at the planet example.  It shows density and radius of planets.   It uses to calculate gravity and i forgot the other part.   This example is confusing me now.  I'm going to go look at some more expanations.

    Thanks,

    Kevin
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:


    The wording in my comments must have wording mistakes.  Part of it feels correct.

    Best,

    Kevin
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    I have a big clue now.

    I clicked on the package in intellij.  I asked to make a new Class.   A window shows up asking the name of the class.  There is a dropdown that allows me to select enum.  Cool!

    This is what is in my enum:



    W3Schools has a good explanation where I can try the code as it explains it.   I'll look at this tomorrow.

    Thanks,

    Kevin
     
    Carey Brown
    Saloon Keeper
    Posts: 10779
    86
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:The wording in my comments must have wording mistakes.  Part of it feels correct.


    Missing a closing brace.
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    I can't find my simple error.  What is stopping me from making an ordinary class?

    I'm going to look at W3Schools for enum and I'm curious to compare it to a  "set".



    Best,

    Kevin
     
    Master Rancher
    Posts: 4905
    74
    • Number of slices to send:
      Optional 'thank-you' note:
    It looks like line 17 has a "}"  just sitting there, not a part of any class, causing confusion.  It looks like it was part of the Kar2 class, but the rest of Kar2 is commented out.  This part has not been commented out, for some reason.
     
    Ron McLeod
    Marshal
    Posts: 4525
    572
    • 1
    • Number of slices to send:
      Optional 'thank-you' note:
    Your code for Kar looks like it should be for a record.
    A class would look like this:
     
    Marshal
    Posts: 8880
    638
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:What is stopping me from making an ordinary class?


    That doesn't look to be Java
    Unless you meant it to be a record?
    Staff note (Liutauras Vilda) :

    Ron's post above beat me to it.

     
    Carey Brown
    Saloon Keeper
    Posts: 10779
    86
    • Number of slices to send:
      Optional 'thank-you' note:
    It's from my post 3 weeks ago and, yes, it's a record.
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Mike,

    Thanks for noticing the } on line (17).    I removed it.

    I still have  a bunch of the same errors.  

    I'll look at more of the replies to see what else is wrong.

    Best,

    Kevin
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Ron and Carey,

    I went back and looked at the code from 3 weeks ago from Carey.

    I just found out that record is a keyword introduced in Java 16.   I have to find out how to use it.

    I used the code from Ron and it got rid of the errors.  The code runs.

    Do you think that I should try to get the "record" way to work?

    I'm looking at this line of code:

    List<Kar> cars = new ArrayList<>();

    I have a list named cars that hold Kar type objects.   Am I saying this correctly?

    Thanks,

    Kevin



     
    Campbell Ritchie
    Marshal
    Posts: 79392
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:. . . Do you think that I should try to get the "record" way to work?

    Yes.

    . . .
    I have a list named cars that hold Kar type objects. . . .

    Not quite; you don't have a List until that reference is assigned to, but a reference of type List.... Most people would call it a List of Kars.

    I have a variable called cars whose declared type is a List of Kars.

    You could also say that in the second line you assign it to an ArrayList of Kars, and that will give you its runtime type.
     * * * * * * * * * * * * * * * * * * * * * * * * *
    A record is particularly good if you make all its fields primitives or immutable reference types.
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    I read an article by a company named Baeldung on the record keyword.   I see that it does a lot of work for us.  

    Their example of a record looks like:
    public record Person (String name, String address){}

    I commented out the working Kar class and want to use it as a record.    I'm including the commented out code  for reference.



    The uncommented part is:



    Where is my error?

    Thanks all,

    Kevin

     
    Marshal
    Posts: 28258
    95
    • Number of slices to send:
      Optional 'thank-you' note:

    package test;

    record Wecord(String name) {}



    Here's some code I wrote. There's no error message.

    But perhaps you missed this in the Baeldung tutorial: "With the release of Java 14..." and tried to compile it with some JDK earlier than that?
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    C:\Users\kevin>java -version
    java version "17.0.7" 2023-04-18 LTS
    Java(TM) SE Runtime Environment (build 17.0.7+8-LTS-224)
    Java HotSpot(TM) 64-Bit Server VM (build 17.0.7+8-LTS-224, mixed mode, sharing)
     
    kevin Abel
    Ranch Foreman
    Posts: 906
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    It turns out that I was using an old version of IntelliJ.    

    i upgraded to the newest version and it recognizes "record".

    The new version says that it is only good for about a month.   Does anyone know how to extend the key?  

    Best,

    Kevin

     
    reply
      Bookmark Topic Watch Topic
    • New Topic
    vceplus-200-125    | boson-200-125    | training-cissp    | actualtests-cissp    | techexams-cissp    | gratisexams-300-075    | pearsonitcertification-210-260    | examsboost-210-260    | examsforall-210-260    | dumps4free-210-260    | reddit-210-260    | cisexams-352-001    | itexamfox-352-001    | passguaranteed-352-001    | passeasily-352-001    | freeccnastudyguide-200-120    | gocertify-200-120    | passcerty-200-120    | certifyguide-70-980    | dumpscollection-70-980    | examcollection-70-534    | cbtnuggets-210-065    | examfiles-400-051    | passitdump-400-051    | pearsonitcertification-70-462    | anderseide-70-347    | thomas-70-533    | research-1V0-605    | topix-102-400    | certdepot-EX200    | pearsonit-640-916    | itproguru-70-533    | reddit-100-105    | channel9-70-346    | anderseide-70-346    | theiia-IIA-CIA-PART3    | certificationHP-hp0-s41    | pearsonitcertification-640-916    | anderMicrosoft-70-534    | cathMicrosoft-70-462    | examcollection-cca-500    | techexams-gcih    | mslearn-70-346    | measureup-70-486    | pass4sure-hp0-s41    | iiba-640-916    | itsecurity-sscp    | cbtnuggets-300-320    | blogged-70-486    | pass4sure-IIA-CIA-PART1    | cbtnuggets-100-101    | developerhandbook-70-486    | lpicisco-101    | mylearn-1V0-605    | tomsitpro-cism    | gnosis-101    | channel9Mic-70-534    | ipass-IIA-CIA-PART1    | forcerts-70-417    | tests-sy0-401    | ipasstheciaexam-IIA-CIA-PART3    | mostcisco-300-135    | buildazure-70-533    | cloudera-cca-500    | pdf4cert-2v0-621    | f5cisco-101    | gocertify-1z0-062    | quora-640-916    | micrcosoft-70-480    | brain2pass-70-417    | examcompass-sy0-401    | global-EX200    | iassc-ICGB    | vceplus-300-115    | quizlet-810-403    | cbtnuggets-70-697    | educationOracle-1Z0-434    | channel9-70-534    | officialcerts-400-051    | examsboost-IIA-CIA-PART1    | networktut-300-135    | teststarter-300-206    | pluralsight-70-486    | coding-70-486    | freeccna-100-101    | digitaltut-300-101    | iiba-CBAP    | virtuallymikebrown-640-916    | isaca-cism    | whizlabs-pmp    | techexams-70-980    | ciscopress-300-115    | techtarget-cism    | pearsonitcertification-300-070    | testking-2v0-621    | isacaNew-cism    | simplilearn-pmi-rmp    | simplilearn-pmp    | educationOracle-1z0-809    | education-1z0-809    | teachertube-1Z0-434    | villanovau-CBAP    | quora-300-206    | certifyguide-300-208    | cbtnuggets-100-105    | flydumps-70-417    | gratisexams-1V0-605    | ituonline-1z0-062    | techexams-cas-002    | simplilearn-70-534    | pluralsight-70-697    | theiia-IIA-CIA-PART1    | itexamtips-400-051    | pearsonitcertification-EX200    | pluralsight-70-480    | learn-hp0-s42    | giac-gpen    | mindhub-102-400    | coursesmsu-CBAP    | examsforall-2v0-621    | developerhandbook-70-487    | root-EX200    | coderanch-1z0-809    | getfreedumps-1z0-062    | comptia-cas-002    | quora-1z0-809    | boson-300-135    | killtest-2v0-621    | learncia-IIA-CIA-PART3    | computer-gcih    | universitycloudera-cca-500    | itexamrun-70-410    | certificationHPv2-hp0-s41    | certskills-100-105    | skipitnow-70-417    | gocertify-sy0-401    | prep4sure-70-417    | simplilearn-cisa    |
    http://www.pmsas.pr.gov.br/wp-content/    | http://www.pmsas.pr.gov.br/wp-content/    |