ConcurrentModificationException java.util.ArrayList$Itr.next [duplicate] - java

This question already has answers here:
How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? [duplicate]
(10 answers)
Closed 3 years ago.
I can be the implementation of a chat app to show users chat only the can get user_id to be sent or receive a message to store in user-list and select the user to be added in the list some error like a User list if added user 1 and add user 2 when and user 1 again the exception in ArrayList
for (String id : usersList)
if (equal(user.getId(), id)) {
if (mUseres.size() != 0) {
for (User user1 : mUseres) {
if (!equal(user.getId(), user1.getId())) {
mUseres.add(user);
}
}
} else {
mUseres.add(user);
}

The issue is here:
for (User user1 : mUseres) {
if (!equal(user.getId(), user1.getId())) {
mUseres.add(user);
}
You are iterating mUseres (for....) and at same time you are adding new items (mUseres.add)

You cant modify the List while iterating through it.
From the docs
Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception

Related

java.lang.UnsupportedOperationException when trying to delete from an #FXML TableView [duplicate]

This question already has answers here:
java.lang.UnsupportedOperationException for removing a row from the javafx tableview
(2 answers)
Closed 4 months ago.
I don't understand why this method wont work because it worked literally three days ago. Whenever I try to use the method(press the button), The database operations work fine but the program throws an error whenever I try to remove from the actual table view so that the user wont see that row anymore. I added a filtered list to the initialize method and i am concerned that might be the cause of the problem. Here is my code:
Initialize Method:
private void initialize()
{
ObservableList<BloomClient> clients = FXCollections.observableArrayList();
firstNames.setCellValueFactory(new PropertyValueFactory<>("FirstName"));
lastNames.setCellValueFactory(new PropertyValueFactory<>("LastName"));
phoneNumbers.setCellValueFactory(new PropertyValueFactory<>("PhoneNumber"));
birthdays.setCellValueFactory(new PropertyValueFactory<>("Birthday"));
startDates.setCellValueFactory(new PropertyValueFactory<>("StartDate"));
endDates.setCellValueFactory(new PropertyValueFactory<>("ExpireDate"));
try {
clients = dBconnect.getClientList();
} catch (Exception e) {
e.printStackTrace();
}
FilteredList<BloomClient> filteredList = new FilteredList<BloomClient>(clients,b -> true);
filteredSearch.textProperty().addListener(((observable, oldValue, newValue) ->
filteredList.setPredicate(person ->
{
if(newValue == null || newValue.isEmpty())
return true;//nothing in text field
String lowerCaseFilter = newValue.toLowerCase();
if (person.getFirstName().toLowerCase().contains(lowerCaseFilter))
return true;//check first name
else if (person.getLastName().toLowerCase().contains(lowerCaseFilter))
return true;//check last name
else
return false;
})
));
SortedList<BloomClient> sortedList = new SortedList<>(filteredList);
sortedList.comparatorProperty().bind(clientList.comparatorProperty());
clientList.setItems(sortedList);
}
public void freezeAccount() throws SQLException, ParseException {
BloomClient person = clientList.getSelectionModel().getSelectedItem();
dBconnect.sendToFreeze(person);//this works
dBconnect.deleteClient(person);//this works
clientList.getItems().remove(person);//java.lang.UnsupportedOperationException
clientList.refresh();
}
Well, it's just a guess. But it's possible that the clientList is a List<> type that was created using Collections.unmodifiableList(). When you try to modify one of those, an UnsupportedOperationException is thrown.
public static List unmodifiableList(List<? extends T> list)
Returns an unmodifiable view of the specified list. This method allows
modules to provide users with "read-only" access to internal lists.
Query operations on the returned list "read through" to the specified
list, and attempts to modify the returned list, whether direct or via
its iterator, result in an UnsupportedOperationException.
See: https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableList-java.util.List-
Figured it out in a way but would like a deeper explanation. I ended up instead of deleting from the clientList(TableView) I deleted directly from the clients(ObservableList) and made that variable global to be reached by other methods. I'm not sure of the reasoning behind the initial problem.
BloomClient person = clientList.getSelectionModel().getSelectedItem();
dBconnect.deleteClient(person);
clients.remove(person);
clientList.refresh();
}

Why null is not equal to null? [duplicate]

This question already has answers here:
How to compare null value from the JsonObject in java
(7 answers)
Closed 3 years ago.
I dont understand what is happening in my application. I'm sending PUT request with updates from Angular project to java api. I have a method that validates query parameters from the put request, the method looks like this:
private JsonObject validateRequestBody(JsonElement requestBody) {
if (!(requestBody instanceof JsonObject)) {
throw new IllegalArgumentException("Request body cannot be case to JSON object");
}
JsonObject bodyObj = requestBody.getAsJsonObject();
System.out.println(bodyObj.get("entityIri").equals(null));
if (bodyObj.get("entityIri") == null) {
System.out.println("null");
throw new IllegalArgumentException("Request body must contain entity IRI");
}
return bodyObj;
}
As you can see, I'm just trying to check if the enityIri paramter is equal to null. To test it, Im sending null as entityIri from Angular project. I tried to compare them with equal method and with ==, but in both cases the output is always false. Could someone explain me why they are not equal? Is it because I'm passing it to JsonObject?
I attach a screenshot from debugging (I cut out irrelevant parts).
Try to use isJsonNull method:
provides check for verifying if this element represents a null value
or not.
if (bodyObj.get("entityIri").isJsonNull()) {
...
}
Of course, you need to check whether bodyObj.get("entityIri") is not null before. I did not add it statement to make statement clear.

How can the map within java.util.HashSet become null [duplicate]

This question already has answers here:
Lazily initialize a Java map in a thread safe manner
(3 answers)
Closed 4 years ago.
I got NullPointerException at myset.contains(obj) and stacktrace like this:
java.lang.NullPointerException: null
at java.util.HashSet.contains(HashSet.java:203) ~[?:1.8.0_131]
I looked in to source code of HashSet,
private transient HashMap<E,Object> map;
...
202 public boolean contains(Object o) {
203 return map.containsKey(o);
204 }
so seems map is null, and my HashSet object is not.
But every init method of HashSet creates a HashMap Object and assigns to map, like
public HashSet() {
map = new HashMap<>();
}
So my question is, why can map become null in line 203?
This happens sometime in our web server, myset is used by multiple threads. I understand there could be inconsistent issue on a non-threadsafe HashSet, but I don't get why it became null.
Thanks in advance.
Post my code here:
Set<String> tags = data.getTags();
if (tags.contains(tmp.toString())) {
return true;
}
class definition of data, which is accessed by multiple threads:
class Data
private Set<String> tags;
public Set<String> getTags() {
if (tags == null) {
tags = new HashSet<String>();
// add something to tags
}
return tags;
}
I think there can be an issue with some other thread, because in this code, it will never change the map. It is just doing conatinsKey check, whoch will not alter the map.
You need to check which places (in various threads), changes are being done in the map, in order to verify that.

Streams: Avoid NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have to get the first element of an array., but it is possible that the element is empty; If the element is empty I put an empty field (I am trying to generate a pdf)
Here is my code now:
public void makePdf(Long id) throws IOException {
Candidacy ca = candidacyRepository.findOne(id);
cos.beginText();
cos.showText(
ca.getInterviews().stream().map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0)!=null?ca.getInterviews().stream().map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0):""));
cos.endText();
}
So I will wish not to prevent the generation of the pdf.
Thank you very much for your support!
UPDATE
Sorry for the lack of precision:
I also sort on the date.
public void makePdf(Long id) throws IOException {
Candidacy ca = candidacyRepository.findOne(id);
cos.beginText();
cos.showText(
ca.getInterviews().stream().sorted((a,b)-> a.getInterviewDate().compareTo(b.getInterviewDate())).sorted((a,f)->f.getInterviewDate().compareTo(a.getInterviewDate())).sorted((b,f)->b.getInterviewDate().compareTo(f.getInterviewDate())).map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0)!=null?ca.getInterviews().stream().sorted((a,b)-> a.getInterviewDate().compareTo(b.getInterviewDate())).sorted((a,f)->f.getInterviewDate().compareTo(a.getInterviewDate())).sorted((b,f)->b.getInterviewDate().compareTo(f.getInterviewDate())).map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0):""));
cos.endText();
}
I get a NullPointerException:/
Thank you for you help
This code doesn't make sense. You are executing the same Stream pipeline twice, and each time you generate an entire List when you only need the first element of that List.
You can use findFirst to get the first element of the Stream.
EDIT :
After testing my original answer, it turned out it doesn't work. findFirst() throws a NullPointerException if the first element is null.
You can avoid that by setting the default value before calling findFirst() :
ca.getInterviews().stream()
.map(Interview::getAgency)
.map(Agency::getAgencyName)
.map(s->s!=null?s:"") // this will replace null with ""
.firstFirst()
.get();

Weird behaviour of ArrayList [duplicate]

This question already has answers here:
Why doesn't this code throw a ConcurrentModificationException?
(3 answers)
Closed 7 years ago.
I have following code -
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1a");
list.add("2b");
for (String s : list) {
list.remove(s);
}
System.out.println("Removed");
System.out.println(list);
}
}
If I run this program, I expect it should throw exception but the output is "2b". If it is running fine then why It is not removing the last object.
Again If I add more element in the list It is thorwing exception java.util.ConcurrentModificationException Which is expected.
My question is -
Why it is not removing all the elements from list if we have 2 elements in the list ??
Why the java.util.ConcurrentModificationException exception occur only when we have more elements ?? I tried a lot of time with two elements.
I am using Java 8.
Thanks in advance.
Actually, when you are removing 1a from the list, the size is getting reduced, and you now have only 1 element in the list, thus the loop does not execute the second time, there by resulting in the keeping the second element.

Categories