Collections

Lists

A List in Java is an interface that behaves very similarly to an array.

  • It's an ordered collection (also known as sequence).

  • The user of this interface has precise control over where each item is inserted in the list.

  • The user can access items by their integer index (position in the list).

  • The user can search for items in the list by looping over the items in it.

Example:

// Database Schema
/*
CREATE TABLE Feedback (
    feedbackId STRING(100) NOT NULL,
    email STRING(100),
    quiz STRING(20),
    feedback STRING(MAX),
    rating INT64,
    score FLOAT64,
    timestamp INT64 )
    PRIMARY KEY (feedbackId);
*/    

// https://google.qwiklabs.com/focuses/1128
  List<Mutation> mutations = new ArrayList<>();

  mutations.add(
                    // TODO: Build a new insert mutation

                    Mutation.newInsertBuilder("Feedback")
                            .set("feedbackId")
                            .to(feedback.getEmail() + '_' +
                                feedback.getQuiz() + "_" +
                                feedback.getTimestamp())
                            .set("email")
                            .to(feedback.getEmail())
                            .set("quiz")
                            .to(feedback.getQuiz())
                            .set("feedback")
                            .to(feedback.getFeedback())
                            .set("rating")
                            .to(feedback.getRating())
                            .set("score")
                            .to(
                            feedback.getSentimentScore())
                            .set("timestamp")
                            .to(feedback.getTimestamp())
                            .build());

ArrayList

An ArrayList is a class that implements the interface List . It's simply a wrapper around an array, but provides really powerful methods that make dealing with the array much simpler.

An item in an ArrayList is known as an element.

Let's have a look at some of the ArrayList's methods:

  • add(E element): Appends the specified element to the end of this list.

  • add(int index, E element): Appends the specified element to the specified index of this list.

  • get(int index): Returns the element at the specified position in this list.

  • contains(Object o): Returns true if this list contains the specified element.

  • remove(int index)

  • size()

.https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

To create and initialize an ArrayList:

ArrayList grades = new ArrayList();

Then you can add elements by add() method:

grades.add(100);
grades.add(97);

// to access first item in the list
grades.get(0); //100

//size of the array
System.out.println(grades.size().toString()); //2

//also remove items by index
grades.remove(0);

//clear the entire list by clear()
grades.clear();

We do not need to specify the array size, unlike arrays.

ArrayList myArrayList = new ArrayList();
int[] myArray = new int[100];

Generics

For example: ArrayLists use Generics to allow you to specify the data type of the elements you're intending to add into that ArrayList.

How

ArrayList<String> listOfStrings = new ArrayList();

Generics eliminate the need for casting

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

When rewritten above one using generics:

List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0); // no cast

Define own Generic Types

.https://docs.oracle.com/javase/tutorial/java/generics/types.html

Collections and Polymorphism

ArrayList<Media> playlist = new ArrayList();

Video someVideo = new Video();
Audio someAudio = new Audio();

playlist.add(someVideo);
playlist.add(someAudio);

Media media = playlist.get(0);
media.play();

ArrayList methods

for(String city : cities) {
  if(city.equals("Sydney")) {
    return true;
  }
}

The indexOf of method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

cities.indexOf("Sydney");

If the above returned -1 then Sydney is not in the list, if it returned any positive value than that will be the index of the String "Sydney".

.https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

HashMap

public class Book {
  String title;
  String author;
  int numOfPages;
  int publishedYear;
  int edition;
  String ISBN;
}

If you were to create a library class that will simulate a virtual library of all the books that exist in the world (~130 Million) you can easily create an ArrayList of Books, and fill it up with all the book details that you may have.

public class Library {
  ArrayList<Book> allBooks;
}

To find book by ISBN:

Book findBookByISBN(String isbn) {
  for(Book book : library.allBooks) {
    if(book.ISBN.equals(isbn)) {
      return book;
    }
  }
}

A way more optimal solution is to use a HashMap instead of ArrayLists.

import java.util.HashMap

public class Library {
  HashMap<String, Book> allBooks;

  allBooks = new HashMap<String, Book>();
}

Then, to add items to the HashMap:

Book taleOfTwoCities = new Book();
allBooks.put("98754236152364", taleOfTwoCities);

//To search for book using ISBN
Book findBookByISBN(String isbn) {
  Book book = allBooks.get(isbn);
  return book;
}

Resources

Last updated

Was this helpful?