Clear the list in do-while loop - java

I am using a do-while loop.In that loop I am having a condition check,whenever the condition fails, the list must get cleared. I am trying but I am not getting the expected result.
List<Date> myDateList=new ArrayList<Date>();
int zTmp=0;
do
{
if(condition true)
{
//do task
}else{
myDateList.clear();
//I wish to clear this list when condition fails
}
zTmp++;
}while(zTmp<myList.size());

I wonder how you can call clear() on ListView.Rather you should consider calling clear on Adapter which is set on ListView.
Below snippet will help you.
adapter.clear();
adapter.notifyDataSetChanged();

Not sure why clear is not working... But work around for this is to assign a new Object to list. So instead using myDateList.clear() you can use myDateList = new ArrayList<T>() or myDateList = new LinkedList<T>().
Just a doubt: Is your condition failing even once?

Related

Add a missing record into the arraylist if it is not in it

Pardon me as I'm quite a beginner in coding. I have tried researching for ways to add some missing record into the lists but still can't seem to fit it correctly into my code.
I have two ArrayLists with different resultsets. Say, the first one is derived in other method and stored in abcList. This list is then used in my current fixChartStats method as a param.
In my code, I will check for the corresponding record in abcList with the second list I derive from the hql query in fixChartStats method.
If the record corresponds, then I'll do the necessary action as shown below to update the ApprovedCount number etc, else i set it to 0.
How do I go about adding the records that are missing in second list I got into the first arraylist (i.e. abcList)? Can anyone here shed some light? Do let me know if my questions are unclear. Thanks in advance, guys!
private void fixChartStats(List<TAbcModel> abcList, Map<String, Object> param, List<IssueModel> issueList, List<DestModel> destList) throws Exception {
//initialize the hql query
//translate all fields from Object[] into individual variable
firstRow = true;
for (TAbcModel abc : abcList) {
if (abc.getId().getAbcYear() = abcYear &&
abc.getId().getAbcMonthId() = abcMonthId &&
abc.getId().getAbcApplAccnId().getAccnId().equalsIgnoreCase(abcApplAccnId.getAccnId()) {
if (firstRow) {
abc.setApprovedCount(abcApprovedCount);
abc.setCancelledCount(abcCancelledCount);
firstRow = false;
} else {
abc.setApprovedCount(0);
abc.setCancelledCount(0);
}
}else{
// How to do the necessary here
// Below is what I've tried
abcList.add(abc);
}
}
}
When I debug, I noticed that it was added into the list. But soon after it was added, ConcurrentModificationException was thrown.
Create a local list and add missing records to it then add all elements from the local list to the abcList
List<TAbcModel> temp = new ArrayList<>();
in your loop:
} else {
temp.add(abc);
}
after loop
abcList.addAll(temp);

Iteration over a Set

I'm having issues with getting an iteration done (and modification) through the Set, which contains Objects. I've tried so many ways of iteration (4), but none of them seem to work and still throw me the Error java.util.ConcurrentModificationException.
[Code is written in Groovy]
private void replaceRock() {
ObjectNodeManager.OBJECTS.each {
System.out.println("Going...");
if(it.getPosition().withinDistance(player.getPosition(), 30)) {
System.out.println("Found...");
Position position = it.getPosition();
ObjectNode newRock = new ObjectNode(439, position, ObjectDirection.NORTH, ObjectType.DEFAULT);
ObjectNodeManager.unregister(it);
ObjectNodeManager.register(newRock);
it.remove();
}
}
}
I've tried synchronization to prevent access from other Threads, but this also didn't work. Please help me, I'm very desperate.
First find them (this will give you basically a list of refs) and then deal with them:
ObjectNodeManager.OBJECTS.findAll {
it.getPosition().withinDistance(player.getPosition(), 30))
}.each{
ObjectNode newRock = new ObjectNode(439, it.position, ObjectDirection.NORTH, ObjectType.DEFAULT)
ObjectNodeManager.unregister(it)
ObjectNodeManager.register(newRock)
it.remove()
}
On a random site note: i'd add a replace method in the ObjectNodeManager to combine unregister, register, remove. Also working with class methods and properties is not the best thing to do (but since it looks like a game...)
The problem is that you are modifying the list of objects while you are looping through the objects.
Try iterating through a copy of the objects instead.
ArrayList<YourType> copy = new ArrayList<YourType>(ObjectNodeManager.OBJECTS);
copy.each(...)

Loop Turning into an Infinite Loop

A segment of my code is triggering an infinite while loop, and I'm not sure why. I've used the loop itself before to add friends to a Linked List in this same program and it worked fine, so I do not understand why it is turning into an infinite loop now.
while (!a.equals("*")){
curr = friendlist.getUsers().getFront();
while (curr!=null){
if (curr.getData().getName().equals(a)){ //why is it not removing friends?
d.removeFriend(curr.getData());
}
curr = curr.getNext();
}
System.out.println("Add a friend by typing in their name. Enter * to end. ");
a = in.nextLine();
}
The above code accesses the following segment from another class:
public void removeFriend(User u){
if (friendsList.isEmpty()){
System.out.println("Empty list, cannot remove.");
}
else{
Node c = friendsList.getFront();
while (c.getNext()!=null){
if (c.getNext().getData().equals(u)){ //condition: if the data is the same
c.setNext(c.getNext().getNext()); //change the link
c.getNext().setData(null); //set the next data to null (cut the link)
friendsList.setSize(friendsList.size()-1);
c = c.getNext();
}
}
}
}
Why is the code not running properly?
As another poster has mentioned, you are invoking the getNext() method twice in one code block.
Here's what I presume is what will work for you
while (c!=null){
if (c.getNext().getData().oldestFriend().getBirthYear()>c.getData().oldestFriend().getBirthYear()){
a = c.getNext().getData();
continue; //then skip the current iteration, so that your line below after the if statement, wont get called.
}
c = c.getNext();
}
Why dont you do this, because now it looks like you're calling that same method three times!
Instead, store whatever is returned from the getNext() into one variable, and then access that local variable and do whatever you want with it, analyse is however you like etc.
Do you know where the infinite loop is exactly? Maybe put a System.out.println("loop") before curr.getNext() and c.getNext() so see which one is failing?
Would add this as a comment, but I'm not yet allowed to :(
How is the semantic of
allUsers.getFront()
Does it just fetch the head or is it more like a pop-operation?
In case of a fetch, there might be an issue with the recursive call of
oldestFriend()
in the method oldestFriend().
Though in that case I would expect a StackOverflowException.
change your while by:
while (c.hasNext() {
Node oldC = c;
c = c.getNext();
if(c.getData().oldestFriend().getBirthYear() > oldC.getData().oldestFriend().getBirthYear()) {
a = c.getData();
}
}
Call only getNext() if there is next, and only once.

How to get the updated list in main method

I am having a list of queues as follows:
public class QueueSelection {
public List initQueueCollection()
{
QueueLoad d1 = new QueueLoad("QUEUEA1", "QUEUEB1", true);
QueueLoad d2 = new QueueLoad("QUEUEA2", "QUEUEB2", false);
QueueLoad d3 = new QueueLoad("QUEUEA3", "QUEUEB3", true);
QueueLoad d4 = new QueueLoad("QUEUEA4", "QUEUEB4", false);
List list = new ArrayList();
list.add(d1);
list.add(d2);
list.add(d3);
list.add(d4);
return list;
}
Now from the main method, i call the above method like,
QueueSelection selection = new QueueSelection();
List<QueueLoad> queueList =selection.initQueueCollection();
When the first input/file comes, queue is checked to see which one of these is false, so I am fetching the second one ("QUEUEA2", "QUEUEB2", false);
As soon as I fetch it, I should change the status to true like ("QUEUEA2", "QUEUEB2", true); I am doing it using
for (QueueLoad s:queueList)
{
if(s.getStatus()==false)
{
str1=s.getQueueName1();
str2=s.getQueueName2();
str3=s.getStatus();
particularCollection=s;
System.out.println(s);
particularCollection.setStatus(true);
particularCollection.setQueueName1(str1);
particularCollection.setQueueName2(str2);
int j=queueList.indexOf(particularCollection);
System.out.println("The index is"+j);
s = new QueueLoad(str1, str2, true);
newqueueList=queueList.set(j, s);
And the list is updated. Now when the second input comes, since in the first line it is seeing the List<QueueLoad> queueList =selection.initQueueCollection();
it is always getting the old list and not the updated one.
Please help.
Now when the second input comes, since in the first line it is seeing
the List queueList =selection.initQueueCollection(); it is
always getting the old list and not the updated one.
I interpret this to mean that you don't want the init method to be invoked again 'when the second input comes'.
There are a lot of ways to address this. Have you considered moving the init method into the constructor for QueueSelection, for example?
Take a look at the javadocs for ArrayList.set. It returns the old value at that location. So you'll want to do:
queueList.set(j, s);
newqueueList = queuelist;
If I have understood you correctly then you're problem is that at each new input you are intializing a new list. Maybe just put queueList as class attribute?
Also:
newqueueList=queueList.set(j, s);
I think set() returns the object that was previously at that index. So your newqueueList would actually contain a QueueLoad object.
Since you haven't shown your main() method, I'm not certain what it looks like, but something along these lines should work:
Instead of:
QueueSelection selection = new QueueSelection();
List<QueueLoad> queueList =selection.initQueueCollection();
Declare queueList outside the method something like this:
private static List<QueueLoad> queueList = null;
Then, in the method,
if (queueList == null)
{
QueueSelection selection = new QueueSelection();
queueList =selection.initQueueCollection();
}

ArrayList remove error

I'm working on a project for school but i'm a little stuck right now
My problem is that i have an arrayList of Squares
Each Square has a value(from 0 to 100). Its starting value is 9999 so i can check if its is checked.
If a square is checked i want it to be removed from the arrayList.
So after a while there will be no Squares left.
there is a little bit of code where the first value is set so thats why i check if the value is 9999.
But i get an error. One that i havent seen before.
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
Vak = Square
this is my code:
while (!vakken.isEmpty()) { // check if empty
Iterator itrVak = vakken.iterator();
while (itrVak.hasNext()) {
Vak vak = (Vak) itrVak.next(); // here is get the error
if (vak.getValue() != 9999) {// check if square value is 9999
Collection checkVakken = vak.getNeighbour().values();
Iterator itre = checkVakken.iterator();
while (itre.hasNext()) {
Vak nextVak = (Vak) itre.next();
if (nextVak != null) {
if (nextVak.getValue() == 9999) {
nextVak.setValue(vak.getValue() + 1); // set value by its neighbour
vakken.remove(vak);
checkvakken.add(vak);
}
}
}
} else {
vakken.remove(vak);
checkvakken.add(vak);
}
}
}
You are removing elements from the collection while you are iterating it. As the iterator may produce unpredictable results in this situation, it fails fast throwing the exception you encountered.
You may only alter a collection through the iterator's methods while traversing it. There should be remove method on the iterator itself, that removes the current element and keeps the iterator intact.
While iterating, you should use Iterator instance for removing object:
itre.remove();
You can try like this:
itre.remove();
ITERATOR never lets you modify when you are iterating.. you need to use loops instead.. this happens coz you are using the Iterator, same time other thread is modifying the list...

Categories

Resources