Loading same value in inner HashMap [duplicate] - java

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 8 years ago.
I am trying to enter the below statement into HashMap
Input Line: Rainy#No:2 Sunny#No:3 Rainy#Yes:3 Sunny#Yes:2 Overcast#Yes:4
Expected Output:{Rainy={No=2,Yes=3},Rainy={No=3,Yes=2},Overcast={Yes=4}}
What I did so far is
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class StackHash{
/**
*#paramargs
*/
staticConcurrentMap<String,HashMap<String,Integer>>map=newConcurrentHashMap<>();
public static final String TAB="\t";
public static final String SPACE=" ";
public static final String HASH="#";
public static final String COLON=":";
public static void main(String[]args){
//TODOAuto-generatedmethodstub
Stringline="Rainy#No:2 Sunny#No:3 Rainy#Yes:3 Sunny#Yes:2 Overcast#Yes:4";
StringTokenizerst=newStringTokenizer(line,SPACE);
HashMap<String,Integer>attibuteCollect=newHashMap<String,Integer>();
while(st.hasMoreTokens()){
Stringtoken1=st.nextToken();
String[]parts=token1.split(HASH);
String[]parts1=parts[1].split(COLON);
attibuteCollect.put(parts1[0],Integer.parseInt(parts1[1]));
if(map.isEmpty()){
map.put(parts[0],attibuteCollect);
}
else{
for(Map.Entry<String,HashMap<String,Integer>>entry:map.entrySet()){
StringkeyMap=entry.getKey();
if(keyMap.equals(parts[0])){
map.put(keyMap,attibuteCollect);
}
else{
map.put(parts[0],attibuteCollect);
}
}
}
}
System.out.println("finalmap"+map);
}
}
Output
map {Rainy={Yes=4, No=3}, Sunny={Yes=4, No=3}, Overcast={Yes=4, No=3}}
Am I doing anything wrong.
Please Suggest.

Reason:
You got ConcurrentModificationException because, you have modified inner attibuteCollect map using put method while iterating over outer map.
Solution:
Use ConcurrentHashMap insted of HashMap to solve ConcurrentModificationException.
ConcurrentMap<String, HashMap<String,Integer>> map = new ConcurrentHashMap<>();

Related

"Variable" cannot be resolved to a variable error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 days ago.
Improve this question
I am getting this error in VSCode Java. One of my variables, DriveConstants keeps having the error saying that it cannot be resolved to a variable. DriveConstants is called in Constants and I do not know if I am doing it right. I am new to Java and don't know why this error is happening. Below is the code that I have for DriveSubsystem:
//DriveSubsystem
package frc.robot.subsystems;
import frc.robot.Constants;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.kinematics.DifferentialDriveOdometry;
import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds;
import edu.wpi.first.wpilibj.ADXRS450_Gyro;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.examples.ramsetecommand.Constants.DriveConstants;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.motorcontrol.VictorSP;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class DriveSubsystem extends SubsystemBase {
// The motors on the left side of the drive.
private VictorSP frontLeftDrive;
private VictorSP backLeftDrive;
private VictorSP frontRightDrive;
private VictorSP backRightDrive;
private final MotorControllerGroup m_leftMotors =
new MotorControllerGroup(
new VictorSP(DriveConstants.kLeftMotor1Port),
new VictorSP(DriveConstants.kLeftMotor2Port));
}
//Constants
package frc.robot;
import edu.wpi.first.math.kinematics.DifferentialDriveKinematics;
public class Constants {
public static final class DriveConstants{
public static final double kTrackwidthMeters=0.96;
public static final DifferentialDriveKinematics kDriveKinematics = new DifferentialDriveKinematics(kTrackwidthMeters);
//EXAMPLE VALUES WILL NEED TO CHANGE
public static final double ksVolts=0.22;
public static final double ksVoltsSecondPerMeter=1.98;
public static final double kaVoltSecondsSquaredPerMeter=0.2;
public static final double kPDriveVel=8.5;
}
public static final class AutoConstants {
//3mph= 1.34112 m/s
//5mph= 2.2352 m/s
public static final double kMaxSpeedMetersPerSecond= 1.34112;
public static final double kMaxSpeedMetersPerSecondSquared=1;
// Reasonable baseline values for a RAMSETE follower in units of meters and seconds
public static final double kRamseteB = 2;
public static final double kRamseteZeta = 0.7;
}
}
Need to import frc.robot.Constants.DriveConstants;

Comparing an array to a single string output using assertEquals in Java

So I would like to create a simple code that greets people according to the input.
The difficulity I have that I have no idea how to compare a simple string with an array, using arrayEquals (or any equivalent).
This is the way I have created the code - according to a previous project:
Test file:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class test {
#Test
public void ShouldGreet() {
assertEquals("Hello, my friend.", new GreetPeople().greeter(""));
assertEquals("Hello, Bob.", new GreetPeople().greeter("Bob"));
}
}
Actual code:
import java.util.Arrays;
public class GreetPeople {
public String greeter(String[] names) {
if (Arrays.stream(names).count() == 1) {
return("Hello, " + names + ".");
}
return("Hello, my friend.");
}
}
Any kind of help is well appreciated!
The first patameter of greeter is an array:
assertEquals("Hello, my friend.", new GreetPeople().greeter(new String[]{""}));
assertEquals("Hello, Bob.", new GreetPeople().greeter(new String[]{"Bob"}));

Why is it not possible to add values to my ArrayList in java after creating an object of iterator

I am learning about collection classes in Java. I created an ArrayList and added some values to it.
package LearningJava;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
public class Java{
public static void main(String args[]) {
Collection values = new ArrayList();
values.add(2);
values.add(3);
values.add(5);
values.add(4);
Iterator itr = values.iterator();
for(int i = 0 ; i<values.size();i++) {
System.out.println(itr.next());
}
}
}
I also iterated through this ArrayList.
If I add values after creating, the object of iterator throws an exception.
package LearningJava;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
public class Java{
public static void main(String args[]) {
Collection values = new ArrayList();
values.add(2);
values.add(3);
values.add(5);
Iterator itr = values.iterator();
values.add(4);
for(int i = 0 ; i<values.size();i++) {
System.out.println(itr.next());
}
}
}
It throws a java.util.ConcurrentModificationException. Why can't I add values after creating the object of iterator?
It is only throwing this exception in case of Iterator interface. When I create the object of other classes, it does not throw any exception.
package LearningJava;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
public class Java{
public static void main(String args[]) {
Collection values = new ArrayList();
values.add(2);
values.add(3);
values.add(5);
// creating the object of scanner instead of iterator's.
Scanner input = new Scanner(System.in);
values.add(4);
Iterator itr = values.iterator();
for(int i = 0 ; i<values.size();i++) {
System.out.println(itr.next());
}
}
}
Here it is not showing any errors. Why is this?
This behaviour is documented in the ArrayList's documentation:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
Adding an element counts as modifying the list "structurally", and note the wording "after the iterator is created".
The modification is detected when you start iterating over the list using next, which is where the exception is thrown.
See also Why is a ConcurrentModificationException thrown and how to debug it for details about what a ConcurrentModificationException is, though that question doesn't specifically address the case where you modify the collection immediately after creating the iterator, without calling next.

Serialize an object into a string [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
Can someone help me to serialze an object into a string? The result of my code is a bit weird, I need to get a toString(); methode or something with which i can serialze an object into a string but I dont know any.
Thanks for the help
results with getString -> only "null"
result without getString(); -> Fruit#4dd8dc3, Fruit#6d03e736, Fruit#568db2f2, Fruit#378bf509, Fruit#5fd0d5ae,
Fruit#2d98a335, Fruit#16b98e56, Fruit#7ef20235"
import java.io.Serializable;
public class Fruit implements Comparable<Fruit>,Serializable{
String getString;
String name;
int gewicht;
public String getString() {
return this.getString;
}
public Fruit(String name, int gewicht) {
this.name=name;
this.gewicht=gewicht;
}
public int compareTo(Fruit otherFruit) {
if(this.gewicht < otherFruit.gewicht)
return -1;
if(this.gewicht>otherFruit.gewicht)
return 1;
return 0;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.TreeSet;
public class FruitTree {
public static void main(String[] args) {
TreeSet<Fruit> fruitTree = new TreeSet<Fruit>();
fruitTree.add(new Fruit("Kiwi",5));
fruitTree.add(new Fruit("Kirsche",1));
fruitTree.add(new Fruit("Ananas",75));
fruitTree.add(new Fruit("Zitrone",15));
fruitTree.add(new Fruit("Grapefruit",44));
fruitTree.add(new Fruit("Banane",55));
fruitTree.add(new Fruit("Kirsche",2));
fruitTree.add(new Fruit("Kiwi",8));
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("IO.txt"));
Iterator<Fruit> it = fruitTree.iterator();
while(it.hasNext()) {
oos.writeObject(it.next());
}
oos.writeObject(null);
ObjectInputStream ois = new ObjectInputStream (new FileInputStream("IO.txt"));
Object readObject=null;
TreeSet<Fruit> deserializedFruits= new TreeSet<Fruit>();
do {
readObject=ois.readObject();
if(readObject !=null)
deserializedFruits.add((Fruit) readObject);
}
while (readObject!=null);
it=deserializedFruits.iterator();
while(it.hasNext()) {
System.out.println(it.next().getString());
ois.close();
oos.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Can someone help me to serialze an object into a string? The result of my code is a bit weird, I need to get a toString(); methode or something with which i can serialze an object into a string but I dont know any.
Thanks for the help
Adding implements Serializable to your class will not override default Object.toString implementation - that's not how Java works (btw this default implementation will actually provide you what you got - for example Fruit#5fd0d5ae - that's how it works)
what you need to do is to override toString by yourself - for example
public class Fruit implements Comparable<Fruit>,Serializable {
// ...
#Override
public String toString() {
return "name: " + this.name + ", gewicht: " + String.valueOf(this.gewicht);
}
}
or to use some existing tool that will generate this method for you (like lombok), or even better that will allow you to serialize your class object to some common format like JSON or XML (for this take a look at gson or Jackson)

Can any of these examples work without using main? Please explain what problems do these examples have besides not having main

//Example 1:
package com.practice;
import java.util.ArrayList;
public class Testing1{
public Testing1()
{
super();
}
public ArrayList getFruits()
{
Arraylist <fruits> = new ArrayList <fruits>();
fruits.add("Orange");
fruits.add("Apple");
fruits.add("grape");
return fruits;
}
}
//Example 2:
package com.practice;
import java.util.ArrayList;
import java.util.List;
public class Testing1{
public Testing1()
{
super();
}
public List getFruits()
{
List <fruits> = new ArrayList<fruits>();
fruits.add("Orange");
fruits.add("Apple");
fruits.add("grape");
return fruits;
}
}
//I made typos on my original code
//contain mycontain; should have been a package name. I corrected that as //well.
//Corrected import java.util.Array.List; to import java.util.Array.List;
//I tried adding a string after List and ArrayList and still does not work //well
//I still don't understand.
//No, this is not a school assignment
//Maybe some can explain which one is correct or the two examples or both //need work? Thank you.
//
All programs need a main method. So no.

Categories