0

I have two different arrays an ArrayList of doubles and an Array of Strings

 public class tester {

        private final static String TIME[]={ "8:00", "9:00", "10:00", "11:00", 
            "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00"  };


        public static void main(String[] args){
            ArrayList<Double> stat = new ArrayList<>();
            stat.add(1.0);
            stat.add(2.0);
            stat.add(3.0);
            stat.add(4.0);
            stat.add(5.0);
            stat.add(6.0);
            stat.add(7.0);
            stat.add(8.0);
            stat.add(9.0);
            stat.add(10.0);
            stat.add(11.0);
            stat.add(12.0);
            int i = 0;
            for (String time : TIME) {
                System.out.println(time+" "+stat.get(i));
                i++;
            }

My question is quite simple is this the best way to loop through each array if I want to get the same position of each array to match? so that stat.get(0) ==TIME.get(0)?

Update

First of all thank you all for your quick response i like the idea of creating a class however there is something you need to know.

The thing you saw was a test class that i use to test my data.

i KNOW that the two arrays will ALWAYS be the same size due to the fact that the stat ArrayList normally defined like the following:

stat is a calculated value of data gained from the database the value of stat is based on time and then sent back to the GUI to be put into a graph and a table.

This means that for each of the TIME there is an exisiting value so that stat.get(0) is ALWAYS equal to TIME.get(0) == "8:00".

With this in mind do you still think i should create a class or should i keep the class showed below and then add a HashMap containing the data then iterate over that map to insert the data in my GUI?

public class Statistics {
    private ArrayList<CallQueue> queues = new ArrayList<CallQueue>();
    private ArrayList<Double> averageData = new ArrayList<Double>();
    private Provider p;

    public Statistics(){
         try {
            this.p = new Provider();
        } catch (DopeDBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * This recursive method calculates the average of each time table and then adds its to the arrayList in the following order:
     * 8.00  = 0
     * 9.00  = 1
     * 10.00 = 2
     * 11.00 = 3
     * 12.00 = 4
     * 13.00 = 5
     * 14.00 = 6
     * ect.
     * @param time
     */
    public void calculateAverage(){
        int data = 0;
        for (int i = 8; i < 20; i++) {
            for (CallQueue cq : queues) {
                data += cq.getCallsByTime(i);
            }
            if (data == 0) {
                Main.createErrorMessage("Fejl i dataen! \r\n kontakt venligst ansvarlige i Dope");
            }
            averageData.add((double) data/11);
        }
    }
    /**
     * @author MRCR
     * This method recives the object list from the database and sets the currentlist to the list recived.
     */
    public void setQueues(Calendar start, Calendar end){
        try {
            queues = p.getInformation(start, end, queues);
        } catch (DopeDBException e) {
            // TODO Auto-generated catch block
            Main.createErrorMessage("Message");
        } catch (DopeResultSetException e) {
            // TODO Auto-generated catch block
            Main.createErrorMessage("Message");
        }

    }
    /**
     * This method returns the calculated DataList list.
     * @author MRCR
     * @return averageData
     */
    public ArrayList<Double>getData(Calendar start, Calendar end){
        setQueues(start, end);
        calculateAverage();
        return averageData;
    }



}


import java.util.HashMap;


public class CallQueue {
    private String type;
    private HashMap<Integer, Integer> data = new HashMap<Integer,Integer>();
    public CallQueue(String type){
        this.type = type;
    }
    public String getType(){
        return type;
    }
    public int getCallsByTime(int time){
        return data.get(time);

    }
    public void addCallsByTime(int hourOfDay, int callAmount) {
        data.put(hourOfDay, callAmount);

    }

}
2
  • 2
    What if the length is not equal?
    – Rohit Jain
    Nov 23, 2012 at 13:12
  • 2
    This is a strong indication that you should define and use a class containing a time and a stat, and iterate over instances of that class.
    – JB Nizet
    Nov 23, 2012 at 13:14

4 Answers 4

4

I would first check that the lengths of the 2 arrays are the same. Then iterate using a for loop:

final int timeLength = TIME.length;
if (timeLength != stat.size()) {
    //something may not be right
}
for (int i = 0; i < timeLength; i++) {
    System.out.println(time[i]+" "+stat.get(i));
}
3
  • @MarvinLabs - I would like to think that the JIT would notice if this value didn't change and would inline the result.... But it is a fair point Nov 23, 2012 at 13:23
  • @MarvinLabs - Sure, but also, the question really wasn't asking about optimising the code, it was about correctness. We could do a few other things, but it would over complicate the answer. Nov 23, 2012 at 13:27
  • I did it this way but don't like it. It would be nice if there were a helper class that could create an iterator on the fly. In the above example, the iterator would check that the lengths are equal during construction, and each iteration would return an object containing time and stat.
    – AndyMan
    Dec 5, 2019 at 15:42
2
for (int i = 0; i < TIME.length; i++) {
  // use i to access TIME[i] and stat.get(i)
}

but you have to ensure that those arrays are of the same length

2
  • No, it's not. This is a needless micro-optimization that probably doesn't optimize anything given that length is a field, and that even if it was a method, it would be inlined by the JIT.
    – JB Nizet
    Nov 23, 2012 at 13:24
  • @MarvinLabs You're right that the middle operand is evaluated every iteration (unless JIT inlines it) but it's not a good practice to leave it outside the loop. And if you think about it, you will spot the right occassion to do this. But not everytime...
    – user219882
    Nov 23, 2012 at 13:32
2

You would need to consider the length part also. You would only need to iterate upto the maximum length possible that covers both array, and list.

So, you can first find the lower length between them. And then iterate till that length: -

int lower = TIME.length < stat.size()? TIME.length: stat.size();

for (int i = 0; i < lower; i++) {
    System.out.println(TIME[i] + " : " + stat.get(i);
}

Now that was the part of iterating over two arrays.

Now I would say, if you have to iterate over two arrays simultaneously, just make a class with the attributes, you have created arrays for.

So, create a class with attributes: - time, and stats. And then create a List<YourClass>. And iterate over the list of the class instances.

2
  • the values in the stat array is a calculated array of a class data that i already have Nov 23, 2012 at 13:41
  • @MarcRasmussen.. Ok. Then you can use the first solution. If the length of array are different, then find the lower length. And if they are same, then no problem..
    – Rohit Jain
    Nov 23, 2012 at 14:15
1
if (TIME.length!=stat.size()) {
    // handle error
}

int count = stat.size();
for (int i=0; i<count; ++i) {
    double d = stat.get(i);
    String s = TIME[i];
}

However

As pointed out in a comment, you should define a class that will gather the information of both arrays.

For instance:

public class MyTime { private double value; private String label; }

Or

In that particular case, I suspect you could use time formatting functions to replace your string array.

String.format("%1$d:00", (int) myDouble);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.