arraylist java.util.ConcurrentModificationException initialize from other class - java

I get the following exception stack trace:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851) at
Controllers.Manager.createTheNetwork(Manager.java:123) at
Controllers.Main.main(Main.java:53)
Why do I get this stack trace? I've just initialized an ArrayList from another class.
Main.java
public class Main {
private static Manager anager;
private static ArrayList<Vfoo> aVfooList;
private static ArrayList<Pfoo> aPfooList;
private static ArrayList<Nfoo> aNfooList;
public static void main(String[] args) {
aPfooList = new ArrayList<Pfoo>();
aVfooList = new ArrayList<Vfoo>();
aNfooList = new ArrayList<Nfoo>();
aPfooList.add(new Pfoo());
aPfooList.add(new Pfoo());
for (Pfoo p : aPfooList)
if (!p.isAMethod())
aVfooList.add(new Cfoo());
aNfooList.add(new Nfoo());
aNfooList.add(new Nfoo());
manager = new Manager();
manager.setList(aList1);
manager.setList(aList2);
manager.createSomething();
}
}
Manager.java
import java.util.ArrayList;
public class Manager {
private ArrayList<Nfoo> nfooList = new ArrayList<Nfoo>();
private ArrayList<Vfoo> vfooList = new ArrayList<Vfoo>();
public NodeManager (){
}
public ArrayList<Nfoo> getNfooList(){
return nfooList;
}
public void addNfooToTheNfooNetwork(Nfoo n){
this.nfooList.add(n);
System.out.println(n);
}
public void addANewVfooToTheNetwork(Vfoo aVfoo){
getNfooList().get(0).addToStack(aVfoo);
}
public void addANewTfooToTheNetwork(Tfoo t, int whichNfoo){
getNfooList().get(whichNfoo).addToStack(t);
}
public void resetNfooNetwork(){
nfooList.clear();
}
public void createSomething(){
for (Nfoo n : nfooList)
addNfooToTheNfooNetwork(n);
for (Vfoo v : vfooList)
addANewVfooToTheNetwork(v);
}
public void createSomething(ArrayList<Nfoo> nl, ArrayList<Vfoo> vl){
this.setNfooList(nl);
this.setVfooList(vl);
for (Nfoo n : nfooList)
addNfooToTheNfooNetwork(n);
for (Vfoo v : vfooList)
addANewVfooToTheNetwork(v);
}
public void setNfooList(ArrayList<Nfoo> nl){
this.nfooList = nl;
}
public void setVfooList(ArrayList<Vfoo> vl){
this.vfooList = vl;
}
}

Indeed, as it is written in the comments you are using Iterators. Check the documentation for the for looping : for (Obj o : objectList)
As #Nagesh Susaria said in the comments, your actual mistake is that you are trying to re-initialize or just add new Nfoo Objects into your ArrayList while the Iterator from the loop is parsing it.
Check the following:
for (Nfoo n : nfooList)
addNfooToTheNfooNetwork(n);
and
public void addNfooToTheNfooNetwork(Nfoo n){
this.nfooList.add(n);
System.out.println(n);
}
As you will see, the "glitch" of your code is in the this.nfooList.add(n); or addNfooToTheNfooNetwork(n); .
Both of them are doing the same I guess. Delete one of them and you are ok!

Related

Using a Java For-Each Loop to iterate over an ArrayList which has private access?

I have three classes: Labradors, Kennels and Show. The Kennel contains a private ArrayList of
Labradors. As shown:
Labradors.java:
public class Labradors {
private String name;
private String description;
public Labradors(String n, String d) {
name = n;
description = d;
}
public String getName() {
return name;
}
}
Kennel.java:
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
}
and
Show.java
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.labs ) {
System.out.println(lab.getName());
}
}
}
My for-each loop in Show gives me the following error:
Show.java:12: error: labs has private access in Kennel
for (Labradors lab: niceHome.labs ) {
^
1 error
Clearly one solution would be to make the ArrayList public, but my understanding of encapsulation is that best practice means it should be private and a Getter written. But how do I do this?
I feel this should have a really easy answer, but I'm having difficulty tracking it down...
NB - I'm using openjdk version 11.0.6 on Ubuntu 19.10.
Inside Kennel Class make a getter function
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
public ArrayList<Labradors> getLabs(){
return this.labs;
}
}
Then access from main function like this
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.getLabs()) {
System.out.println(lab.getName());
}
}
}

How to set a value on a class using another class that is called/set in main class

I have 3 classes, say: ShareType, ShareTypesTrue and Main.
public class ShareType {
public String shareTypeName = "";
public String noOfShare = "";
public String parValue = "";
public void setShareTypeName(String shareTypeName) {
this.shareTypeName = shareTypeName;
}
public void setNoOfShare(String noOfShare) {
this.noOfShare = noOfShare;
}
public void setParValue(String parValue) {
this.parValue = parValue;
}
}
public class ShareTypesTrue {
public List<ShareType> shareType;
public void setShareType(List<ShareType> shareType) {
this.shareType = shareType;
}
}
public class Main {
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
sharetypetrue.add(shareTypeName);
}
Now my problem is i need to set shareTypeName to a value under the class ShareTypesTrue. Meaning i have to use ShareTypesTrue to call on the Sharetype class and set the shareTypeName.
Anyone has an idea?
NOTE: I cant change/add code in the first 2 classes except in main. i just need to find a way to get around this.
Thanks Alot
Please check below code for Main class.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]){
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
//Create object
ShareType shareType = new ShareType();
shareType.setShareTypeName("Original Name");
//Create list
List<ShareType> shareTypes=new ArrayList<ShareType>();
shareTypes.add(shareType);
//Attach it to share
sharetypetrue.setShareType(shareTypes);
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
//Editing it.
for(ShareType shareTypesMember:sharetypetrue.shareType){
shareTypesMember.shareTypeName = "Updated Name";
}
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
}
}
Use Sharetype class to set the shareTypeName
ShareType share = new ShareType();
share.setShareTypeName("name");
share.setNoOfShare("no");
share.setParValue("val");
List<ShareType> shareType = new ArrayList<ShareType>();
shareType.add(share);
use ShareTypesTrue to set Sharetype
ShareTypesTrue sharetrue = new ShareTypesTrue();
sharetrue.setShareType(shareType);//pass ShareType as list
If you want to set the 'name' in ShareType, what prevents you from doing the below:
class ShareTypeTrue_Extended extends ShareTypeTrue{
protected shareTypeName;
public ShareTypeTrue_Extended(String shareTypeName){this.shareTypeName=shareTypeName;}
public void setShareType(List<ShareType> shareType) {
for(ShareType s: shareType)s.setShareTypeName(this.shareTypeName);
super.setShareType(shareType);
}
}

HashMap : Find a Value from a Key from different class

first take a look of my code so far here:
main program
public static void main(String[] args) {
KamusService service = new KamusService();
IKamus idKeEn = new IDKeEN();
String artiBelajar = service.cariArtiKata("belajar",idKeEn);
String artiPintu = service.cariArtiKata("pintu",idKeEn);
System.out.println(artiBelajar);
System.out.println(artiPintu);
}
KamusService class
public class KamusService {
public String cariArtiKata(String cariArtiKata, IKamus n) {
return n.terjemahkan();
}
idKeEn class
public class IDKeEN extends IKamus {
Map<String,String> id2en = new HashMap<String,String>();
public IDKeEN() {
id2en.put("belajar","learning");
id2en.put("pintu","door");
}
#Override
public String terjemahkan() {
return id2en.get("pintu");
}
}
and IKamus class
public abstract class IKamus {
public abstract String terjemahkan();
}
i wonder how to put "belajar" from String artiBelajar to my HashMap inside IDKeEN class as a key so main program can print String artiBelajar
From above you can see that my program's output is "door" because inside IDKeEN class it override the output.
i just wanna know how to make this line work
String artiBelajar = service.cariArtiKata("belajar",idKeEn);
use "belajar" as a Key for my HashMap and idKeEn as the destination class to process the whole things.
Thanks.

Java varargs to require indefinite number of variables

I am trying to apply varargs. I have declared a method which requires an indefinite amount of variables like this:
private Subject carMonitor;
public AdvancedMonitor(Subject ... carMonitors){
for (Subject carMonitor : carMonitors){
this.carMonitor = carMonitor;
carMonitor.registerObserver(this);
}
}
However, when I try to call it in my main method, I am not able to use anything other than one argument:
BigCar bigCar = new BigCar();
SmallCar smallCar = new SmallCar();
AdvancedMonitor doubleAdvancedDisplay1 = new AdvancedMonitor();
AdvancedMonitor doubleAdvancedDisplay2 = new AdvancedMonitor(bigCar);
AdvancedMonitor doubleAdvancedDisplay3 = new AdvancedMonitor(bigCar, smallCar);
Only the second one works. Why is this?
Is it related to my interface?
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
big car interface -- small car is pretty much the same for now :
public class BigCar implements Subject {
private ArrayList observers;
private int state;
public BigCar(){
observers = new ArrayList();
}
public void registerObserver(Observer o){
observers.add(o);
}
public void removeObserver(Observer o){
int i = observers.indexOf(o);
if (i >= 0){
observers.remove(i);
}
}
public void notifyObservers(){
for (int i = 0; i < observers.size(); i++){
Observer observer = (Observer)observers.get(i);
observer.update(state);
}
}
public void stateChanged() {
notifyObservers();
}
public void setState(int state){
this.state = state;
stateChanged();
}
}
I write following code:
public class Test {
public static class AdvancedMonitor {
private String carMonitor;
public AdvancedMonitor(String... carMonitors) {
for (String carMonitor : carMonitors) {
this.carMonitor = carMonitor;
System.out.println(this.carMonitor);
}
}
}
public static void main(String[] args) {
String bigCar = "bigCar";
String smallCar = "smallCar";
System.out.println("step 1");
AdvancedMonitor doubleAdvancedDisplay1 = new AdvancedMonitor();
System.out.println();
System.out.println("step 2");
AdvancedMonitor doubleAdvancedDisplay2 = new AdvancedMonitor(bigCar);
System.out.println();
System.out.println("step 3");
AdvancedMonitor doubleAdvancedDisplay3 = new AdvancedMonitor(bigCar, smallCar);
}
}
And I have following result:
step 1
step 2
bigCar
step 3
bigCar
smallCar
In my opinion, all correct. What is wrong in your case? Do you use logging or System.out.println to debug your problem? It's look like your problem isn't with Java varagrs, but you have some exception in carMonitor.registerObserver(this).
P.S. Also, you understand that every AdvancedMonitor has only a one varible carMonitor? And using new AdvancedMonitor(bigCar, smallCar); in result you have AdvancedMonitor only with smallCar in private String carMonitor;?
P.P.S. Also bad idea to use this in construstor, because object isn't really create when running construstor.
Actually the Constructor works.
Please check these statements:
SmallCar and BigCar both implements Subject
class AdvancedMonitor implements Observer
AdvancedMonitor doubleAdvancedDisplay is not declared several times but in your code it is. It should be smth like:
AdvancedMonitor doubleAdvancedDisplay1 = new AdvancedMonitor();
AdvancedMonitor doubleAdvancedDisplay2 = new AdvancedMonitor(bigCar);
AdvancedMonitor doubleAdvancedDisplay3 = new AdvancedMonitor(bigCar, smallCar);
I hope it'll help you

Odd Null Pointer Exception

I'll get right to it.
So I have code that gets a Null Pointer Exception. I've tried looking up what causes it and how to fix it, but that's why I'm confused with this particular code. It was working just fine earlier today and now its throwing the exception. Any help? I'm probably just overlooking something silly but it's quite frustrating. Code follows:
import java.util.*;
import java.io.*;
public class ShopMain<T> {
List<T> stock;
public void Shop() { stock = new LinkedList<T>(); }
public T buy() { return stock.remove(0); }
void sell(T item) { stock.add(item); }
void buy(int n, Collection<? super T>items) {
for (T e : stock.subList(0, n)) {
items.add(e);
}
for (int i=0; i<n; ++i) stock.remove(0);
}
void sell(Collection<? extends T> items) {
for (T e : items) {
stock.add(e);
}
}
public static void main (String[] args) {
ShopMain<Marker> paintballShop = new ShopMain<Marker>();
Console console = System.console();
System.out.println("1 - Test Suite");
String input = console.readLine("Please select the corresponding number to your choice.\n");
if(input.equals("1")){
Stack<Marker> stack = new Stack<Marker>();
Set<Marker> hashset = new HashSet<Marker>();
System.out.println("Test Suite : Tests List, Stack, HashSet");
paintballShop.sell(new Geo3());
paintballShop.sell(new Ego11());
paintballShop.buy();
paintballShop.buy(2, stack); //Stack use
paintballShop.sell(stack); //Stack use
paintballShop.buy(3, hashset); //HashSet
paintballShop.sell(hashset); //HashSet
System.out.println("Tests Complete");
}
}
}
Exception error occurring at runtime:
Exception in thread "main" java.lang.NullPointerException
at ShopMain.sell(ShopMain.java:14)
at ShopMain.main(ShopMain.java:39)
These last bits are just class 'placeholders' for the objects and their parent class.
public class Marker{}
public class Geo3 extends Marker{}
public class Ego11 extends Marker{}
Thanks again for any help.
That's because your List List<T> stock; is still uninitialized. You need to initialize it for you to be able to add, remove elements to/from it. By default, its null and thus, when you try to call a method on it, you get the NullPointerException.
This happens because you don't have a constructor at all. Shop() is not the constructor of your class. A constructor has the same name as the class, and thus you need to have your constructor like this
public ShopMain() { stock = new LinkedList<T>(); }
Incase, Shop() is a valid method, then you need to call this method so that your list is initialized and only then call the other methods.
paintballShop.Shop(); // Call this method to init your list.
change to constructor..
public ShopMain() { stock = new LinkedList<T>(); }
You probably need to change:
public void Shop() { stock = new LinkedList<T>(); }
//doesn't look a method name, may be this is what you missed
to
public ShopMain() { stock = new LinkedList<T>(); }
You don't have a constructor for ShopMain that initializes your List.
Add this:
ShopMain() {
stock<T> = new ArrayList<T>();
}
Basically it comes do to the fact that stock is never initialised. I imagine that the class use to be called Shop
You could change...
public class ShopMain<T> {
List<T> stock;
public void Shop() {
stock = new LinkedList<T>();
}
To...
public class ShopMain<T> {
List<T> stock;
public ShopMain() {
stock = new LinkedList<T>();
}
Which will initialise the List when the class is constructored...

Categories