简体   繁体   中英

Initializing 2D ArrayList for for-loop summation (Java)

I am trying to sum N pairs of ints--an Nx2 ArrayList--and return the N summations as an ArrayList. While I understand it is not necessary to set up a class to accomplish this, I would like to do so as practice for future projects.

import java.util.ArrayList;

public class SumsInLoop {
    public SumsInLoop(int numberOfPairs, ArrayList<ArrayList<Integer>> numbersList) {}

    public ArrayList<Integer> getSums(int numberOfPairs, ArrayList<ArrayList<Integer>> numbersList) {
        ArrayList<Integer> pairsOfSums = new ArrayList<Integer>();
        for (ArrayList<Integer> Pair : numbersList) {
            int x = Pair.get(0);
            int y = Pair.get(1);
            int sum = x + y;
            pairsOfSums.add(sum);
        }
        System.out.println(pairsOfSums);
        return pairsOfSums;
    }

The data that I am given is a random assortment of N pairs (numbersOfPairs) of integers, eg 612673 108695. I would like to add these pairs of integers to a 2D ArrayList (numbersList) that will be called by getSums.

However, I am having difficulties initializing numbersList. My main function is as follows:

    public static void main(String[] args) {
        int myNumberOfPairs = 13;
        ArrayList[][] myNumbersList = new ArrayList[13][2];
        myNumbersList[0][0] = new ArrayList<>();
        myNumbersList[0][0].add(612673);
        myNumbersList[0][1].add(108695);
        myNumbersList[1][0] = new ArrayList<>();
        myNumbersList[1][0].add(756875);
        myNumbersList[1][1].add(496058);
        SumsInLoop mySum = new SumsInLoop(myNumberOfPairs,myNumbersList);
        mySum.getSums(myNumberOfPairs, myNumbersList);

The last two lines of code throw errors, asking me to change myNumbersList to type ArrayList<List<Integer>> which throws even more errors, even after changing all 2D ArrayLists to type ArrayList<List<Integer>> .

So, my two questions are as follows:

  1. How can I initialize an NxM ArrayList and populate it correctly?
  2. Is there a faster way of accomplishing this task while still using a class method?

PS I'm used to coding in Python and am self-teaching myself Java, so any other information or resources you can provide me with are much appreciated.

The (compile) exception you are getting is due to the fact that you expect a ArrayList<ArrayList<Integer>> , but pass an ArrayList[][] . (which is not the same in Java)

  1. In your case you'd need (in the main method):

     ArrayList<ArrayList<Integer>> myNumbersList = new ArrayList</* when java > 6 ;)*/>(13); 

    this only sets the capacity of the (parent) list (..and the underlying/internal backing array) to initialize the child lists, you'd not come around looping (somehow...even not in python :):

     for (int i = 0; i < 13; i++) { myNumbersList.add(new ArrayList<Integer>(2)); } 

    Depends on what means "correctly" ...but I assume with "random data", ideally you would again inner loop:

     java.util.Random rnd = new Random(/*seed default current timestamp*/); //... for (int i = 0; i < 13; i++) { ArrayList<Integer> innerList = new ArrayList<>(2); for (int j = 0; j < 2; j++) { innerList.add(rnd.netxInt(/*bound default Integer.MAX_VALUE*/) /*+/-/% offset*/); } myNumberList.add(innerList); } 
  2. Sorry I am not aware of one (faster way), but much depends on the "input format".

Since you already know the amount of values in a pair, an ArrayList is unnecessary. You can create your own, simpler implementation of a pair.

class Pair {
    public final int left;
    public final int right;

    public Pair(int left, int right){
        this.left = left;
        this.right = right;
    }
}

You can then access the values by creating a pair object and accessing its fields.

Pair p = new Pair(10, 7);
System.out.println(p.left); // 10
System.out.println(p.right); // 7

You can then more easily redefine your getSums method.

public static List<Integer> getSums(List<Pair> pairs){
    List<Integer> pairsOfSums = new ArrayList<>();
    for(Pair pair : pairs){
        int sum = pair.left + pair.right;
        pairsOfSums.add(sum);
    }
    return pairsOfSums;
}

Please also notice the function can be static and you don't need to pass the number of pairs. The for-each loop will cycle through all of them regardless.


Initializing the array is then easier than the method you have described in the question.

List<Pair> pairs = new ArrayList<>();
pairs.add(new Pair(7, 10));
pairs.add(new Pair(18, 3));
pairs.add(new Pair(-6, 0));
pairs.add(new Pair(4, 2));
System.out.println(SumsInLoop.getSums(pairs));

You may want to simplify your input by using 2D array of int : int[][] myNumbersList = new int[13][2];
The expected output in that case is a 1D array of int[13] that can be obtained as follows (demonstrated with 2 pairs. See mcve ) :

public class SumsInLoop {
    //pairsOfInts should be an [n][2] array
    private static int[] sumOfPairs(int[][] pairsOfInts) {

        int[] sums = new int[pairsOfInts.length];
        for(int pairIndex = 0; pairIndex < pairsOfInts.length; pairIndex++) {
            sums[pairIndex]= pairsOfInts[pairIndex][0]+pairsOfInts[pairIndex][1];
        }
        return sums;
    }

    public static void main(String[] args) {
        int numberOfPairs = 2;
        int[][] pairsOfInts = new int[numberOfPairs][2];
        pairsOfInts[0] = new int[] {612673,108695 };
        pairsOfInts[1] = new int[] {756875,496058 };
        int[] sumOfPairs = sumOfPairs(pairsOfInts);
        System.out.println(Arrays.toString(sumOfPairs));
    }
}

If you want a solution implemented with List you can make use of javafx Pair (or make your own pair class.
The input can be defined as List<Pair<Integer,Integer>> pairsOfInts = new ArrayList<>();
The out put can be an array as above, or a List<Integer> :

import java.util.ArrayList;
import java.util.List;
import javafx.util.Pair;

public class SumsInLoop {

    private static List<Integer> sumOfPairs(List<Pair<Integer, Integer>> pairsOfInts) {
        List<Integer> sums = new ArrayList<>();
        for(Pair<Integer,Integer> pair : pairsOfInts) {
            sums.add(pair.getKey()+ pair.getValue());
        }
        return sums;
    }

    public static void main(String[] args) {
        List<Pair<Integer,Integer>> pairsOfInts = new ArrayList<>();
        pairsOfInts.add (new Pair<>(612673,108695 ));
        pairsOfInts.add (new Pair<>(756875,496058));
        List<Integer> sumOfPairs = sumOfPairs(pairsOfInts);
        System.out.println(sumOfPairs); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM