ArrayList in Java
Operations :
1 . eclare an ArrayList of different Types
D
2. Add Element
3. Get Element
4. Add Element at a specific Index
5. Set Element at a specific Index
6. Delete Element from an Index
7. Size of the List
8. Loop/Iterate on the List
9. Sort the List
import
java
.
u
til
.
A
rrayList
;
import
java
.
u
til
.
C
ollections
;
class
ArrayLists
{
public
static
void
main
(
S
tring
args
[]) {
ArrayList
<
Integer
>
list
=
new
ArrayList
<
I
nteger
>();
ArrayList
<
String
>
list2
=
new
ArrayList
<
S
tring
>();
ArrayList
<
Boolean
>
list3
=
new
ArrayList
<
B
oolean
>();
//add elements
list
.
a
dd
(
1
);
list
.
a
dd
(
3
);
list
.
a
dd
(
4
);
list
.
a
dd
(
5
);
System
.
out
.
println
(
l
ist
);
//to get an element
int
element
=
list
.
g
et
(
0
);
// 0 is the index
System
.
out
.
println
(
e
lement
);
//add element in between
list
.
a
dd
(
1
,
2
);
// 1 is the index and 2 is the
element to be added
System
.
out
.
println
(
l
ist
);
//set element
Apna College
list
.
s
et
(
0
,
0
);
System
.
out
.
println
(
l
ist
);
//delete elements
list
.
r
emove
(
0
);
// 0 is the index
System
.
out
.
println
(
l
ist
);
//size of list
int
size
=
list
.
s
ize
();
System
.
out
.
println
(
s
ize
);
//Loops on lists
for
(
int
i
=
0
;
i
<
list
.
s
ize
();
i
++) {
System
.
out
.
p
rint
(
list
.
g
et
(
i
) +
" "
);
}
System
.
out
.
println
();
//Sorting the list
list
.
a
dd
(
0
);
Collections
.
sort
(
list
);
System
.
out
.
println
(
l
ist
);
}
}
Homework Problems
Try solving all problems of arrays with arraylists.
Apna College