android ArrayList iterator - java

I am trying to use an iterator on an ArrayList ( to get rid of a for loop, don't ask me why... ), however I need to skip the process of one of the arrays upon a boolean condition , should I still use an index and a break ???
// INTERPOLATION
int i = 0;
Iterator<CircularFifoQueue<SensorEvent>> buf = samplingFifoQueues.iterator();
while (buf.hasNext()) {
if ( i == 2 && !mDeviceSensorGyro) { // skip this queue if no gyroscope in device
break;
}
// proceed
buf.next();
i++;
}
thanks for help

What about this:
// INTERPOLATION
int i = 0;
Iterator<CircularFifoQueue<SensorEvent>> buf = samplingFifoQueues.iterator();
while (buf.hasNext()) {
if ( i != 2 || mDeviceSensorGyro) { // skip this queue if no gyroscope in device
// proceed
}
buf.next();
i++;
}
But I would rather attach some attribute to the queue elements to check for it. Work directly with numbers is bad practice.

Related

Java 8, While Loop: Reduce the total number of break and continue statements in this loop to use at most one

I've got a class which contains the following:
while (true) {
// if minimum element in the queue is greater than required sweetness
// then we are done
if (queue.peek() >= minSweetness) {
solutionPossible = true;
break;
} else {
// if there are more than or equal to 2 elements,
// then only solution is possible
// because we have already checked queue.peek() for the single element
// present, and that is less than minSweetness
if (queue.size() >= 2) {
// remove minimum and 2nd minimum values
int a1 = queue.poll();
int a2 = queue.poll();
// again push the value to the queue
// after calculating the combined sweetness
queue.offer(a1 + 2 * a2);
} else {
// for single element that is less than required sweetness
// no solution is possible
solutionPossible = false;
break;
}
// increase total number of operations
operations++;
}
}
Here is a screenshot:
VScode tells me to reduce the total number of break and continue statements in this loop to use at most one,
so I am not as experienced as to what other method I can think of, I tried to used quick fix and It didn't work,
anybody has any idea how to write this class differently...?
I tried to use quick fix and it didn't show other options though...
Assuming you need to preserve the original structure of the loop (i.e. while (true) ) then this is one method of complexity reduction (comments removed):
while (true)
{
if (queue.peek() >= minSweetness || queue.size() < 2) {
solutionPossible = (queue.peek() >= minSweetness);
break;
}
int a1 = queue.poll();
int a2 = queue.poll();
queue.offer(a1 + 2 * a2);
operations++;
}
The two loop "breaks" are condensed into one. The difference in their processing is the setting of the solutionPossible which can be set based on the first condition.
The else is removed as unnecessary.
If peek were a costly operation (which it likely is not) then assigning the result to variable first would be an optimization since it is used twice.
Instead of coding the while as an infinite loop, and breaking out of it, use a variable to control loop continuation or exit. In this case, I chose a boolean:
boolean decided = false;
while ( ! decided ) {
// if a minimum element in the queue is
// greater than the required sweetness
// then we are done
if (queue.peek() >= minSweetness) {
solutionPossible = true;
decided = true;
} else {
// if there are more than or equal to 2 elements,
// then only solution is possible
// because we have already checked
// queue.peek() for the single element
// present, and that is less than minSweetness
if (queue.size() >= 2) {
// remove minimum and 2nd minimum values
int a1 = queue.poll();
int a2 = queue.poll();
// again push the value to the queue
// after calculating the combined sweetness
queue.offer(a1 + 2 * a2);
} else {
// for a single element that is
// less than the required sweetness
// no solution is possible
solutionPossible = false;
decided = true;
}
// increase the total number of operations
operations++;
}
}
By the way, I like retaining the first break. It's a style preference:
boolean decided = false;
while ( ! decided ) {
// if a minimum element in the queue is
// greater than the required sweetness
// then we are done
if (queue.peek() >= minSweetness) {
solutionPossible = true;
decided = true;
break;
// if there are more than or equal to 2 elements,
// then only solution is possible
// because we have already checked
// queue.peek() for the single element
// present, and that is less than minSweetness
if (queue.size() >= 2) {
...
Retaining the first break allows elimination of the first else, reducing the nesting level by one for the code that follows.

Android, String Array can't go BACKWARDS from [0] TO [6(last String)] (Button = Button -1), CRASH

Whenever my back_button reaches the String[0] and I try proceeding going backwards my App just crashes.
Instead of simply going from String[0] to my currently last string [6] and continue to go backwards (if the conditions are met), why it doesnt do that ?
My code for that Button, btw im new to programming and I know my Code is EXTREMLY TRASH.. but, that's another topic, please xD :
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward_button.setVisibility(View.GONE);
backButton();
if (mediator == 10) {
forward_button.setVisibility(View.VISIBLE);
backk--;
display.setText(list[backk]);
}
if (backk == currentnumber-5 ) {
back_button.setClickable(false);
}
if (backk != currentnumber-5) {
back_button.setClickable(true);
back_button.setEnabled(true);
}
if (mediator != 10){
back_button.setEnabled(false);
display.setText(list[currentnumber]);
}
}
});
Btw. I thought it maybe has something to do with this Code right here in my other's Button Logic, maybe there is a similiar function to call for when going from String [0] to String [last string(6)] ?
if (currentnumber == list.length) {
currentnumber = 0;
backk = 0;
back = 1;
EDIT : I deleted if ( backk < 0 ) { ... , I dont know why it was in there to begin with, sorry, that wasnt supposed to be in there.
In your block, make the following change:
if (mediator == 10) {
forward_button.setVisibility(View.VISIBLE);
backk--;
// If we go below the size of the array, add the array
// size to loop back to the last element in the array
if (backk < 0){
backk += list.length;
}
display.setText(list[backk]);
}
If you explain what it is you're trying to accomplish and post more of your code, I might be able to help clean up your code a little with comments on why I make the choices I do. But the change above will fix that array out of bounds crash.

Dynamically change for-loop range in Java

Is there a way to increase the for-loop range in java? I have the following code:
for (DataRoot bri : Ri)
{
for (DataRoot brcom : complemento)
{
if (bri.getMesa().equals(brcom.getMesa()))
{
if (found) {found = false; break;}
postrecom = brcom.getOrden().getPostres();
Calendar dateri = Calendar.getInstance();
Calendar datecom = Calendar.getInstance();
dateri.setTime(bri.getFechaorden());
for (Postres proc : postrecom)
{
// if (found) {found = false; break;}
datecom.setTime(proc.getHora_plato());
long diff = datecom.getTimeInMillis() - dateri.getTimeInMillis();
if ( diff > (3*60*1000))
{
found = true;
Ri.add(brcom);
break;
}
else
{
bri.getOrden().getPostres().add(proc);
setBase();
}
}
}
}
}
As you can notice, if some conditions are met, the Array "Ri" which is the main array will increase its content, lets say from 3 items to 4, at the start, the loop was going to be from 0 to 2 but as it got a new element I need it to keep running from 0 to 3 but the range will not dynamically increase as new items are added.
I could count how many items I added to "Ri" So that I can call that many times this method but if I do so, the compiler witll give me the "java.util.ConcurrentModificationException" error at this point I dont know what to do any help would be appreciated.
I might be wrong, but from the explanation you have given and code you have written, you are trying to get complement Items and then add them to Ri list if not present.
Assuming data structure of Ri is ArrayList, the way I would approach is that, first I would get all the complement items. Then loop through complement items, and for each complement item, loop through the entire Ri value and set a boolean if the associated value is suitable to add like below :
for(dataBri brCom : complemento) {
boolean shouldAdd = false;
for (DataBri bri : Ri) {
if(someConditionMet) {
shouldAdd = true;
}
if (shouldAdd) {
Ri.add(brCom);
}
}
I hope it makes sense.
Well im relatively new developing in Java and seems like if you do loop type For-each like
for (Arraylist arraylist : size)
{
....
}
assuming your initial size was 2, meaning that the array contains 2 elements, IF in the process you add elements to the array, the size wont dynamically change BUT if you go for the old
for (int i = 0; i < Arraylist.size(); i++)
{
....
}
and in the process you add elements to the Array, the size of the loop gets re-calculated dynamically as you add new elements to the array and in my case, solving my problem.

Count elements of a list using While loop in java

I am passing some parameters in the URL and then I add them in a list. My list has a limit of 5 elements. So if someone adds 6th element in the URL the list would simply ignore it. So I am trying to use a counter but the logic is not working as desired. I am using While loop to achieve this. So if list size is smaller than 5 set the agencyCds otherwise just return the list.
private List<IUiIntegrationDto> generateViewIntegrationReportData(ESignatureIntegrationConfig eSignConfig) throws Exception {
int counter = 1;
if(eSignConfig.getAdditionalAgencyCds() != null ) {
List<String> combinedAgencyCds = new ArrayList<String>();
for(String agencyCd : eSignConfig.getAgencyCd()) {
combinedAgencyCds.add(agencyCd);
}
StringTokenizer token = new StringTokenizer(eSignConfig.getAdditionalAgencyCds().toString(), StringConstants.COMMA);
while(token.hasMoreTokens()) {
combinedAgencyCds.add(token.nextToken());
}
while(combinedAgencyCds.size() < 5) {
counter = counter + 1;
eSignConfig.setAgencyCd(combinedAgencyCds);
}
// eSignConfig.setAgencyCd(combinedAgencyCds);
}
List<IUiIntegrationDto> intgList = getUiIntegrationManager().retrieveUiIntegrationReportData(eSignConfig.getAgencyCd(), eSignConfig.getCreatedDays(),
eSignConfig.getLob(), eSignConfig.getTransactionStatus(), eSignConfig.getAccounts(), eSignConfig.getSortKey(), eSignConfig.getSortOrder());
return intgList;
}
I am not completely sure about this logic if it is correct or if there is nay better approach.
Thanks
Try this instead of the last while in your code:
if(combinedAgencyCds.size() <= 5) {
eSignConfig.setAgencyCd(combinedAgencyCds);
} else {
eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, 5));
}
The full combined list will then be used if it is less than 5 in size. Otherwise, only the first 5 elements are used.
Edit: Or even better:
eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, Math.min(5, combinedAgencyCds.size())));
Ok so let's break down what your code is currently doing.
int counter = 1;
while(combinedAgencyCds.size() < 5) {
counter = counter + 1;
eSignConfig.setAgencyCd(combinedAgencyCds);
}
This snippet of code has a couple things wrong best I can tell. First, this loop has the possibility of running forever or not at all. Because combinedAgencyCds is never being manipulated, the size won't ever change and the logic being checked in the while loop never does anything. Second, there's a more efficient loop for doing this, assuming you don't need the counter variable outside of its usage in the while loop and that is using for loops.
Example syntax is as follows:
for (int i = 0; i < combinedAgencyCds.size(); i++) {
if (i < 5) {
// Do your logic here.
}
else {
break; // Or handle extra values however you want.
}
}
Notice there is no need for the explicit declaration for a counter variable as "i" counts for you.
Now in your actual logic in the loop, I'm not sure what the setAgencyCd method does, but if it simply sets a list variable in the eSignConfig like it appears to, repeating it over and over isn't going to do anything. From what I can see in your code, you are setting a variable with the same value 5 times. If you need any more explanation just let me know and I will be happy to revise the answer.

Limit in For-Each Loop

I'm a beginner in Java and a geomatics student.
I work with an XTF image, its works like TIFF. This image store about 20000 lines called pings with several informations : coordinates, start time, stop time... The treatments I use on Intellij become too heavy but it works well.
I want to cut in two the informations stored in my XTF image :
1 image with the 10000 first pings and the other with the 20000 last pings. Later I would gather the two images.
My question is simple : how, with a “for each” loop can I order a limit (<=10000) ? I stored the information in a csv file.
for (XtfPing ping : xtf.getPings())
{
writer.write( Double.toString( ping.x) );
writer.write( "," );
writer.write( Double.toString( ping.y) );
writer.write( "\n" );
}
writer.close();
I know this doesn't fit exactly the OP's situation, but maybe this will help someone else looking to implement an iterate limit using Java 8:
List<Object> myList = ...
List<Object> first10000 = myList.stream().limit(10000).collect(Collectors.toList());
for (Object obj : first10000) {
// do stuff
}
or more simply:
List<Object> myList = ...
myList.stream().limit(1000).forEach(o -> {
// do stuff
});
If you must you an enhanced for loop, you must introduce your own counter in order to test the number of iterations :
int limit = 0;
for (XtfPing ping : xtf.getPings())
{
if (limit <= 10000) {
// do something
} else {
// do something else
}
limit++;
}
An alternative (if getPings() returns a Collection that supports random access (such as List) or an array) is to replace your enhanced for loop with a traditional for loop, in which the iteration number is built in.
For example, if getPings returns a List :
for (int i = 0; i < xtf.getPings().size(); i++)
{
XtfPing ping = xtf.getPings().get(i);
if (i <= 10000) {
// do something
} else {
// do something else
}
}
You can use an int to increment every loop and a break; to stop the for loop
int i = 0;
for (XtfPing ping : xtf.getPings()) {
(if i <= amountOfLoops) {
writer.write( Double.toString( ping.x) );
writer.write( "," );
writer.write( Double.toString( ping.y) );
writer.write( "\n" );
} else {break;}
}
writer.close();

Categories