main
  • About
  • Civil Engineering
    • Interview questions
    • Bridge design
  • Google Cloud
    • Code samples
    • kafka
    • Cloud Run
    • persistent disks
    • Spinnaker
    • Assessment questions
    • IAM
    • Cloud Storage
    • VPC
    • Cost optimization
    • Compute Engine
    • App Engine
    • Cloud Vision
    • Spanner
    • Cloud SQL
    • Solutions
      • Static IP - WIP
      • Network performance
      • Building a VPN
      • Build a streaming app
      • ML train with taxi data
    • Dataproc
    • Dataprep
    • BigTable
    • Cloud Fusion
    • Data flow
    • CloudFront
    • APIGEE
    • BigQuery
    • Cloud logging
    • Pubsub
    • Identity Aware Proxy
    • Data center migration
    • Deployment Manager
    • Kubeflow
    • Kubernetes Engine
    • Istio
    • Read the following
    • Storage for cloud shell
    • kms
    • kpt
    • Hybrid cloud with Anthos
    • helm
    • Architecture
    • terraform
    • Network
    • Data studio
    • Actions
    • Jenkins
  • Data Processing
    • Data Lake
    • Data ingestion
    • Data Cleaning - Deduplication
    • Data Cleaning - Transformation
    • Data cleaning - rule definition
    • ETL
  • Machine Learning
    • Tensorflow
    • Tensorflow tips
    • Keras
    • Scikit-learn
    • Machine learning uses
    • Working with Pytorch
    • Federated learning
  • AWS cloud
    • Billing
    • Decrease volume size of EC2
    • Run CVE search engine
    • DataSync
    • EC2 spot instances
  • Java
    • Java
    • NIO
    • System Design
      • Zero trust framework
    • Collections
  • Azure
    • Enterprise Scale
    • API
    • Resource group
    • Create an sql database
  • UBUNTU
    • No Release file
    • STRATO blockchain
    • iperf
    • Rsync
    • curl
    • Shell
    • FAQ - git
  • PH test
    • Syllabus
    • Opportunities
    • Aptitude test
  • Development
    • Course creation
    • web.dev
    • docfx template
  • npm
  • Docker Desktop
  • Nginx
  • English rules
  • Confluent
  • sanity theme
  • Java Native Interface tutorial
  • Putty
  • Personal website host
  • Google search SEO
  • Reading a textbook
  • DFCC Progress
  • STORAGE
    • Untitled
  • Services Definition
    • Cloud VPN and routing
  • Microservices design and Architecture
    • Untitled
  • Hybrid network architecture
    • Untitled
  • Deployment
    • Untitled
  • Reliability
    • Untitled
  • Security
    • Untitled
  • Maintenance and Monitoring
    • Peering
  • Archive
    • parse dml to markdown
Powered by GitBook
On this page
  • Lists
  • ArrayList
  • Generics
  • Collections and Polymorphism
  • ArrayList methods
  • HashMap
  • Resources

Was this helpful?

  1. Java

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()

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

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".

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

PreviousZero trust frameworkNextEnterprise Scale

Last updated 4 years ago

Was this helpful?

.

.

.

https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
https://docs.oracle.com/javase/tutorial/java/generics/types.html
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
https://dzone.com/articles/a-deep-dive-into-collections
https://classroom.udacity.com/courses/ud283