Skip to content

Commit f60261a

Browse files
committed
ArrayList lesson & examples added
1 parent 4d66b21 commit f60261a

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

src/ArrayList.kt

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
fun main() {
2+
3+
/*
4+
5+
ArrayList class is used to create a dynamic array.
6+
Which means the size of ArrayList class can be increased or decreased according to requirement.
7+
ArrayList class provides both read and write functionalities.
8+
9+
ArrayList class follows the sequence of insertion order.
10+
ArrayList class is non synchronized and it may contains duplicate elements.
11+
The elements of ArrayList class are accessed randomly as it works on index basis.
12+
13+
*/
14+
15+
val arrayList = ArrayList<String>() // Creating an empty arraylist
16+
arrayList.add("Kotlin")
17+
arrayList.add("Java")
18+
arrayList.add("Swift")
19+
arrayList.add("Objective-C")
20+
21+
// print ArrayList elements
22+
for (language in arrayList) {
23+
24+
println("Mobile Programming Language : $language")
25+
}
26+
27+
28+
// Let's create an ArrayList class with initialize its initial capacity.
29+
// The capacity of ArrayList class is not fixed and it can be change later in program according to requirement.
30+
val ageList = ArrayList<Int>(3)
31+
ageList.add(12) // Adding object in ageList
32+
ageList.add(21)
33+
ageList.add(33)
34+
35+
for (age in ageList) {
36+
37+
println("Age : " + age)
38+
}
39+
40+
41+
// arrayList size
42+
println("size of ageList : ${ageList.size}")
43+
44+
45+
// The get() function of ArrayList class is used to retrieve the element present at given specified index.
46+
println("ageList.get(1) : ${ageList.get(1)}")
47+
48+
49+
// The set() function of ArrayList class is used to set the given element at specified index and replace
50+
// if any element present at specified index.
51+
ageList.set(0, 45)
52+
53+
54+
// The indexOf() function of ArrayList class is used to retrieve the index value of first occurrence of element or
55+
// return -1 if the specified element in not present in the list.
56+
println(ageList.indexOf(45))
57+
58+
59+
// new element add
60+
ageList.add(45)
61+
62+
// The lastIndexOf() function of ArrayList class is used to retrieve the index value of last occurrence of
63+
// element or return -1 if the specified element in not present in the list.
64+
println(ageList.lastIndexOf(45))
65+
66+
67+
// The remove () function of ArrayList class is used to remove the first occurrence of element if it is
68+
// present in the list.
69+
ageList.remove(12)
70+
71+
72+
// The removeAt() function of ArrayList class is used to remove the element of specified index from the list.
73+
ageList.removeAt(2)
74+
75+
76+
// The clear() function of ArrayList class is used to remove (clear) all the elements of list.
77+
ageList.clear()
78+
}

0 commit comments

Comments
 (0)