ArrayLists
tip
REFERENCE:~
- Official Documentation:-
Java 14
java.util.ArrayList
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/ArrayList.html - ....
note
ArrayList
is part of the Java Collections
Library.
- Unlike arrays, Collections do not have the
[]
operator.So, we use theget()
method to access an element by its index. - There is one restriction,
Collections
cannot store primitive values at all (int
,long
,char
,double
,boolean
and so on). We must use one of the wrapper classes (Integer
,Long
,Character
,Double
or another one) instead.
Declaration
info
ArrayList<Integer> al = new ArrrayList<>();
// Default Capacity is 10
// al.size() = 0; /* No. of Elements */
ArrayList<Integer> al = new ArrayList<>(50);
// al.size() = 0;
// capacity = 50;
ArrayList<String> newList = new ArrayList<>(listToBeCopied);
//construct an ArrayList "newList" that consists of elements of another list "listToBeCopied"
Initialisation from user input
info
- If total input is unknown👇:
ArrayList<Integer> al = new ArrayList<>();
while(sc.hasNext()) { //takes input till there is any input left
al.add(sc.nextInt());
}
info
- If the user input is in many lines and we have to assign the input in each line to a new ArrayList:
/* Input is:
45 565 65 65 65
4 44 5 65 66 6 64 6
4 4 54 54 44 654
*/
ArrayList<Integer> al1 = new ArrayList<>();
ArrayList<Integer> al2 = new ArrayList<>();
ArrayList<Integer> al3 = new ArrayList<>();
for (String el : sc.nextLine().split("\\s+")) { //using for-Each loop to take input from a single line as "String" and Convert it to Integer using "Integer.parseInt()" and then "added" it to ArrayList "al1"
al1.add(Integer.parseInt(el));
}
for (String el : sc.nextLine().split("\\s+")) { //using for-Each loop to take input from a single line as "String" and Convert it to Integer using "Integer.parseInt()" and then "added" it to ArrayList "al2"
al2.add(Integer.parseInt(el));
}
for (String el : sc.nextLine().split("\\s+")) { //using for-Each loop to take input from a single line as "String" and Convert it to Integer using "Integer.parseInt()" and then "added" it to ArrayList "al3"
al3.add(Integer.parseInt(el));
}
- All the given inputs👆 have a
lot of "spaces"
; So, usefor - Each
loop to take a whole single line asnextLine()
and thensplit("\\s+")
the line into separate strings and then useInteger.parseInt()
to convert theString
intoInteger
and thenadd()
the convertedinteger
to theArrayList
"al". - Then repeated the same way to take all other lines as separate inputs for separate ArrayLists.
Always use "\\s+"
to match whitespaces
the regular expression
\s
or\\s
matches a single whitespace character ;; while\s+
or\\s+
will match one or more whitespace characters. https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/regex/Pattern.html
- The regular expression
\s
is a predefined character class. It indicates a single whitespace character.- The plus sign
+
is a Greedy Quantifier, which means one or more times.For example, expression X+ matches one or more X characters
.
info
- If total input is known:
ArrayList<Integer> al = new ArrayList<>();
input1 = sc.nextInt();
input2 = sc.nextInt();
input3 = sc.nextInt();
input4 = sc.nextInt();
al.add(input1);
al.add(input2);
al.add(input3);
al.add(input4);
ArrayList<Integer> al = new ArrayList<>();
al.add(sc.nextInt());
al.add(sc.nextInt());
al.add(sc.nextInt());
Printing ArrayList
info
for (String el : al) {
System.out.print(el + " ");
} //using "for-Each" loop
for (int i=0; i<al.size(); i++) {
System.out.print(al.get(i) + " "); // use get() for accessing an element at a particular index
}
System.out.println(al);
// It prints:
// [Hello, second, Third, fourth]
MultiDimensional ArrayLists
ROW
given & COL
not given
info
/* Input is:
4
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
*/
int row = sc.nextInt();
sc.nextLine();
ArrayList<ArrayList<Integer>> al = new ArrayList<>();
for (int i = 0; i < row; i++) {
ArrayList<Integer> tempAl = new ArrayList<>();
for (String el : sc.nextLine().split("\\s+")) {
tempAl.add(Integer.parseInt(el));
}
al.add(tempAl);
}
// Printing 2D ArrayList
for (ArrayList<Integer> el : al) {
for (int el2 : el) {
System.out.print(el2 + " ");
}
System.out.println();
}
/*
Output is:
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
*/
ROW
unknown & COL
unknown
info
/* Input is:
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
hello
*/
ArrayList<ArrayList<Integer>> al = new ArrayList<>();
while (sc.hasNextInt()) {
ArrayList<Integer> tempAl = new ArrayList<>();
for (var el : sc.nextLine().split("\\s+")) {
tempAl.add(Integer.parseInt(el));
}
al.add(tempAl);
}
String end = sc.next();
// Printing 2D ArrayList
for (ArrayList<Integer> el : al) {
for (int el2 : el) {
System.out.print(el2 + " ");
}
System.out.println();
}
System.out.println("A example of line added at the End is: " + end);
/*
Output is:
2 4 6 8 10 12
4 5 6 7 8 9
1 2 2 2 51 5
56 5 15 5 56 5
A example of line added at the End is: hello
*/
❤️🔥 Great Example of 2D ArrayList
along with other inputs
❤️🔥
caution
The starting unknown number of lines of Input is given for 2D ArrayList and last two numbers are given for other operations.
/*
Input is:
2 4 6 8 10 12
4 5 6 100 8 9
1 2 2 2 51 5
56 5 15 5 56 5
100 45 // 👉 These are to be removed for other operations
*/
import java.util.Scanner;
import java.util.ArrayList;
import java.util.*;
class Try {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// int row = sc.nextInt(), col = 6;
// sc.nextLine();
ArrayList<ArrayList<Integer>> al = new ArrayList<>();
while (sc.hasNextInt()) {
ArrayList<Integer> tempAl = new ArrayList<>();
for (var el : sc.nextLine().split("\\s+")) {
tempAl.add(Integer.parseInt(el));
}
al.add(tempAl);
}
// Printing 2D ArrayList
for (ArrayList<Integer> el : al) {
for (int el2 : el) {
System.out.print(el2 + " ");
}
System.out.println();
}
int lastRowInd = al.size() - 1;
int lasColInd = al.get(lastRowInd).size() - 1;
System.out.println("lastelement is " + al.get(lastRowInd).get(lasColInd));
// al.remove(lastRowInd);
// al.get(lastRowInd).remove(lasColInd);
int extra1 = al.get(lastRowInd).get(lasColInd);
al.get(lastRowInd).remove(lasColInd); // 1
int extra2 = al.get(lastRowInd).get(lasColInd - 1);
al.get(lastRowInd).remove(lasColInd - 1); // 0
System.out.println("extra1: " + extra1 + " extra2: " + extra2 + " and sum is: " + (extra1 + extra2));
System.out.println();
// Printing "MODIFIED" 2D ArrayList
for (ArrayList<Integer> el : al) {
for (int el2 : el) {
System.out.print(el2 + " ");
}
System.out.println();
}
}
}
- Output is 👇
2 4 6 8 10 12
4 5 6 100 8 9
1 2 2 2 51 5
56 5 15 5 56 5
100 45
lastelement is 45
extra1: 45 extra2: 100 and sum is: 145
2 4 6 8 10 12
4 5 6 100 8 9
1 2 2 2 51 5
56 5 15 5 56 5
ArrayList
Methods
size()
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(78);
al.add(90);
al.add(898);
System.out.println(al.size());
get()
- Takes Index No. and returns the element at that particular Index.
ArrayList<String> al = new ArrayList<>();
al.add("Hello");
al.add("second");
al.add("Third");
al.add("fourth");
System.out.println(al.get(2)); //It prints "Third"
add()
add(int index, element x)
adds a passed element to the specified position of the collection;add(int index, element x)
add the element at that index and pushes current element backward;
ArrayList<String> al = new ArrayList<>();
al.add("onlyAdd1"); // add(element x)
al.add("onlyAdd2");
al.add("onlyAdd3");
al.add("onlyAdd4");
al.add(2, "Index+Add"); // add(int index, element x)
addAll()
addAll(Collection c)
method for adding the whole collection to an ArrayList. It appends elements of the provided collection to the end of the list.
note
Collection c
means it can take any type of Collections such as ArrayList
, LinkedList
and others...
// "al1" and "al2" are two ArrayLists
// al1 has [100, 89, 90, 890]
// al2 has [66, 6846]
al2.addAll(al1); // al2 becomes [66, 6846, 100, 89, 90, 890]
set()
set(int index, elements x)
replaces the element present at the specified index with the given element "x";
ArrayList<String> al = new ArrayList<>();
al.add("onlyAdd1");
al.add("onlyAdd2");
al.add("onlyAdd3");
al.add(2, "Index+Add");
al.add("onlyAdd4");
al.set(3, "replacedaElement") // set(int index, element x)
remove()
remove(element x)
removes the first occurrence of the specified element from this list, if it is present;remove(int index)
removes the element at the specified position in this list;
ArrayList<String> al = new ArrayList<>();
al.add("onlyAdd1");
al.add("onlyAdd2");
al.add("onlyAdd3");
al.add(2, "Index+Add");
al.add("onlyAdd4");
al.remove("onlyAdd3"); //remove(element x)
al.remove(1) //remove(int index)
clear()
clear()
removes all elements from the ArrayList.
al.clear();
contains()
contains(element x)
returns Boolean valuetrue
orfalse
- Checks whether an ArrayList contains that given element or not
- It is caseSensitive in case of String elements
ArrayList<String> al = new ArrayList<>();
al.add("hidj");
al.add("dhsi");
al.add("dhis");
al.add("djsioj");
System.out.println(al.contains("DHIS")); //returns false
System.out.println(al.contains("dhis")); //returns true
indexOf()
indexOf()
finds the 1st occurance of given element
ArrayList<String> al = new ArrayList<>();
al.add("hidj");
al.add("dhsi");
al.add("dhis");
al.add("dhsi");
System.out.println(al.indexOf("dhsi")); //prints index: "1"
lastIndexOf()
lastIndexOf()
finds the last occurance of given element
ArrayList<String> al = new ArrayList<>();
al.add("hidj");
al.add("dhsi");
al.add("dhis");
al.add("dhsi");
System.out.println(al.lastIndexOf("dhsi")); //prints index: "3"
clone()
info
MUST
do typecasting :~ al1 = (ArrayList) li1.clone();
- Returns a shallow copy of this ArrayList
ArrayList<Integer> al = new ArrayList<>();
ArrayList<Integer> li = new ArrayList<>();
while (sc.hasNext()) {
li.add(sc.nextInt());
}
System.out.println(li);
al = (ArrayList) li.clone();
System.out.println(al);
forEach()
caution
If you are already familiar with method references or lambda expressions, you can use another style for iterations using the
forEach(Consumer<T> consumer)
method:
languages.forEach(System.out::println); // with method reference
languages.forEach(elem -> System.out.println(elem)); // with lambda expression
Collections.___(ArrayListName)
note
All the methods of java.util.Collections
can be applied on ArrayList
info
Collections.sort(ArrayListName)
Collections.addAll(ArrayListName, "element1", "element2", "element3")
Collections.reverse(ArrayListName)
- ....
- ...
- ...
- ...
2D ArrayDeque
to 2D ArrayList
caution
import java.util.*;
class Try {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// int row = sc.nextInt(), col = 6;
// sc.nextLine();
ArrayDeque<ArrayDeque<Integer>> ad = new ArrayDeque<>();
while (sc.hasNextInt()) {
ArrayDeque<Integer> tempAl = new ArrayDeque<>();
for (var el : sc.nextLine().split("\\s+")) {
tempAl.offerLast(Integer.parseInt(el));
}
ad.offerLast(tempAl);
}
for (ArrayDeque<Integer> el : ad) {
for (int el2 : el) {
System.out.print(el2 + " ");
}
System.out.println();
}
int extra1 = ad.peekLast().pollLast();
int extra2 = ad.peekLast().pollLast();
System.out.println("extra1: " + extra1 + " extra2: " + extra2 + " and sum is: " + (extra1 + extra2));
System.out.println();
for (ArrayDeque<Integer> el : ad) {
for (int el2 : el) {
System.out.print(el2 + " ");
}
System.out.println();
}
System.out.println("Conversaion from ArrayDeque to ArrayList");
ArrayList<ArrayList<Integer>> al = new ArrayList<>();
for (ArrayDeque<Integer> el : ad) {
ArrayList<Integer> al2 = new ArrayList<>(el);
al.add(al2);
}
// Printing The New ARRAYLIST
for (ArrayList<Integer> el : al) {
for (int el2 : el) {
System.out.print(el2 + " ");
}
System.out.println();
}
}
}