Saman
Saman

Reputation: 523

How to create 2 Dimensional ArrayList and set values it in Java?

I have a 2 dimensional array and fill it at start :

public static String [][] BooksList =
    {
        {"Coders at Work",null},
        {"Code Complete",null},
        {"The Mythical Man Month",null},
        {"Don’t Make Me Think, Revisited",null},
        {"The Pragmatic Programmer",null}
    };

I want to add more rows anytime. But array class doesn't allow increase the size of array. So i must use ArrayList like this :

ArrayList<List<String>> BooksList= new ArrayList<List<String>>();

But i don't know how to fill it like arrays.

Upvotes: 0

Views: 943

Answers (3)

davidxxx
davidxxx

Reputation: 131346

According to your comment :

It is the simple library system that anytime can add book and every book also have name of person that borrowed it.

You should probably use a Map where the key is a book and the value is a List of borrower (as a book may probably have been booked by several people).
Using a map will ease the retrieval/modification of a specific book.
With array or List, when you want to access/change a specific book, you have to iterate the List until finding it.

You could so create a Map with books :

Map<Book, List<Borrower>> borrowersByBook = new HashMap<>();
borrowersByBook.put(new Book("Coders at Work"), new ArrayList<>());
borrowersByBook.put(new Book("Code Complete"), new ArrayList<>());
...

And add borrowers for books :

 List<Borrower> borrowers = borrowersByBook.get(new Book("Coders at Work"));
 borrowers.add(new Borrower("SaMi GiMiX", LocalDate.of(2017, 8, 12));
 borrowers.add(new Borrower("davidxxx", LocalDate.of(2017, 8, 12));

If you use a Book class instead of a String class to represent a book, you have to override equals()/hashcode() methods.

Upvotes: 2

Hugo sama
Hugo sama

Reputation: 909

A two dimensional array can be represented with lists like this :

List<List<String>> BooksList = new ArrayList<>();
//adding elements
BooksList.add( Arrays.asList("ONE","TWO") );
//or like this
List<String> row = new ArrayList<>();
row.add("THREE");
row.add("FOUR");
BooksList.add(row);

Upvotes: 1

Jonathan
Jonathan

Reputation: 46

You can add items to the list like this:

BooksList.add(Arrays.asList("Cool book", null));

Upvotes: 2

Related Questions