Home > Software engineering >  Add null values to 2d List with Generics
Add null values to 2d List with Generics

Time:04-09

I'm trying to create a two-dimensional List of a table that holds a single type of object with predefined rows and columns and initialize all cels as null, but it wont pass the test below why?

public class Tab<E> {

    public Tab(int rows, int columns) {
        List<List<E>> listOfLists = new ArrayList();
        for (int i = 0; i < rows;   i) {
            List<E> list = new ArrayList();
            listOfLists.add(list);
            for (int j = 0; j < columns;   j) {
                list.add((E) null);
            }
        }
    }
}

Test:

Tab<Integer> tab;
tab = new Tab<>(2, 3);
boolean allNull = tab.toList().stream().allMatch(Objects::isNull);

CodePudding user response:

Constructors can not return any value. if you want to have a list first of all put your code in a method and after that by returning the two dimensional array and streaming on it you would get the correct answer

public List<List<E>> myarrays(int rows, int columns){
        List<List<E>> listOfLists = new ArrayList();
        for (int i = 0; i < rows;   i) {
            List<E> list = new ArrayList();
            listOfLists.add(list);

            for (int j = 0; j < columns;   j) {
                list.add((E) null);
            }

        }

        return listOfLists;
    }

and after that you can use this:

  boolean allNull = tab.myarrays(2,3).stream().filter(a ->a==null).allMatch(Objects::isNull);

CodePudding user response:

The purpose of a constructor is to create an instance of a class and [usually] to also initialize the class fields. I think you need to make listOfLists a class field.

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

public class Tab<E> {
    private List<List<E>> listOfLists;

    public Tab(int rows, int columns) {
        listOfLists = new ArrayList<>(rows);
        for (int i = 0; i < rows;   i) {
            List<E> list = new ArrayList<>(columns);
            listOfLists.add(list);
            for (int j = 0; j < columns;   j) {
                list.add((E) null);
            }
        }
    }

    public static void main(String[] args) {
        Tab<Integer> tab = new Tab<>(2, 3);
        boolean allNull = tab.listOfLists.stream() // returns a stream where the type of each element is 'List<E>'
                                         .flatMap(lst -> lst.stream()) // returns a stream where the type of every element is 'E'
                                         .allMatch(Objects::isNull);
        System.out.println(allNull);
    }
}
  • Related