Using a List instead of an array

Java 8.3.2012 2 Comments

Lists and arrays can both be used to store ordered collections of data. Both have their strengths and weakness which we shall discuss in a later post.

Previously we showed you how to generate Pascals Triangle and in that Java example we used arrays to represent each row of the triangle.

The following code shows what the code would look like if we replace the use of arrays with List’s.

package com.learnjava.math;

import java.util.ArrayList;
import java.util.List;

 * Write a Java program that calculates the 
 * first 10 lines of a Pascals Triangle
 * @author

public class PascalTriangleUsingList {

	public static void main(String[] args) {
		int n = 10;
		List<Integer> row = new ArrayList<Integer>();
		for (int i=0; i<n; i++) {
			// Calculate next row
			row = pascalRow(row);

			// Output row
			// First add some padding so triangle is centered
			for (int j=0; j< n - i; j++) {
				System.out.print(" ");
			// Now output the row values
			for (int j=0; j< row.size(); j++) {
				System.out.print(row.get(j)+" ");

	public static List<Integer> pascalRow(List<Integer> previous) {
		// Row is 1 element longer than previous row
		List<Integer> row = new ArrayList<Integer>(previous.size() + 1);
		// Initialise the list
		// Unlike arrays, a list is empty until we add values to it
		for (int i=0; i<previous.size()+1; i++) {

		// First and last numbers in row are always 1
		row.set(0, 1);
		row.set(row.size() - 1, 1);
		// The rest of the row can be 
		// calculated based on previous row
		for (int i = 1; i< row.size()-1; i++) {
			row.set(i, previous.get(i-1) + previous.get(i));
		return row;

2 Responses to “Using a List instead of an array”

  1. Sandy Lee

    how come when i seperate the main and the Arraylist into two classes
    row1 = pascalRow(row1); gets error and say i need to create it and i did do

    PascalTriangle pas = new PascalTriangle();

    Thank You

  2. Thats because the pascalRow() method is then in a different class
    You would need to use:

    row1 = pas.pascalRow(row1);

Leave a Reply