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:
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.
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:
Then you can add elements by add()
method:
We do not need to specify the array size, unlike arrays.
Generics
For example: ArrayList
s use Generics to allow you to specify the data type of the elements you're intending to add into that ArrayList
.
How
Generics eliminate the need for casting
When rewritten above one using generics:
Define own Generic Types
Collections and Polymorphism
ArrayList methods
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.
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
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.
To find book by ISBN:
A way more optimal solution is to use a HashMap instead of ArrayList
s.
Then, to add items to the HashMap:
Resources
Last updated
Was this helpful?