1import java.util.ArrayList;
2public class ArrayListGetExample
3{
4 public static void main(String[] args)
5 {
6 ArrayList<String> al = new ArrayList<String>();
7 al.add("lion");
8 al.add("tiger");
9 al.add("deer");
10 al.add("cheetah");
11 al.add("elephant");
12 al.add("fox");
13 al.add("hyenas");
14 al.add("jackal");
15 System.out.println("Get second element of ArrayList: " + al.get(1));
16 System.out.println("Get third element of ArrayList: " + al.get(2));
17 System.out.println("Get fifth element of ArrayList: " + al.get(4));
18 System.out.println("Get sixth element of ArrayList: " + al.get(5));
19 }
20}
1example on ArrayList set(int index, E element) method for IndexOutOfBoundsException
2import java.util.ArrayList;
3public class ArrayListSetMethodExample
4{
5 public static void main(String[] args)
6 {
7 try
8 {
9 ArrayList<Integer> al = new ArrayList<Integer>();
10 al.add(36);
11 al.add(23);
12 al.add(39);
13 al.add(69);
14 al.add(56);
15 System.out.println("ArrayList before using set() method: " + al);
16 // replace number at the index 7 with 25
17 System.out.println("Trying to replace the element at index greater than capacity: ");
18 int num = al.set(7, 25);
19 // printing modified ArrayList
20 System.out.println("ArrayList after using set() method: " + al);
21 // printing replaced element
22 System.out.println("Replaced number: " + num);
23 }
24 catch(IndexOutOfBoundsException ex)
25 {
26 System.out.println("Exception: " + ex);
27 }
28 }
29}
1import java.util.ArrayList;
2public class ArrayListSetMethodExample
3{
4 public static void main(String[] args)
5 {
6 ArrayList<String> names = new ArrayList<String>(5);
7 names.add("vinay");
8 names.add("ajay");
9 names.add("vijay");
10 names.add("bharat");
11 names.add("dinesh");
12 System.out.println("ArrayList before using set() method: " + names);
13 // change vijay name to chandan
14 System.out.println("ArrayList after using set() method: ");
15 names.set(2, new String("chandan"));
16 for(int a = 0; a < 5; a++)
17 {
18 System.out.println(names.get(a).toString());
19 }
20 }
21}