-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayList
70 lines (59 loc) · 1.82 KB
/
ArrayList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.ArrayList;
import java.util.List;
public class ArrayLists {
public static void main(String[] args) {
// Basic 2D array
String[] games = { "Risk", "Monopoly", "Cards Against Humanity" };
// Arrays, like strings, are based with index 0
System.out.println(games[2]);
/// ArrayList of size 5 but index 0-4
ArrayList<String> fruits = new ArrayList<String>(5);
fruits.add("Apples");
fruits.add("Oranges");
fruits.add("Peaches");
fruits.add("Kiwis");
// Index will be One, everything else will shift
fruits.add(1, "Bananas");
// Size is 5, adjusts to filled index not capacity
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
// Not add, but change value at index
fruits.set(1, "grapes");
// Cannot access out of size
// fruits.set(6, "fries");
// ArrayList Methods
// Default Capacity of 10
ArrayList<String> moreFruits = new ArrayList<String>();
moreFruits.add("apple");
moreFruits.add("peach");
moreFruits.add("banana");
moreFruits.add("kiwi");
System.out.println(moreFruits);
//Adding to fruits
moreFruits.add(1,"grapes");
System.out.println(moreFruits);
//Inclusive 1, exclusive 4
System.out.println(moreFruits.subList(1, 4));
//Index methods apply
System.out.println(moreFruits);
int index=moreFruits.indexOf("apple");
System.out.println(index);
//Copy the Method
ArrayList <String> newList = new ArrayList <String> (moreFruits);
System.out.println(newList);
//Array list are objects, not primitives. This method takes advantages of autoboxing
List<Integer> intList=new ArrayList <Integer> ();
for (int number = 1 ; number <= 20 ; number++)
{
intList.add(number);
}
System.out.println(intList);
int total=0;
for (int number: intList)
{
total+=number;
}
System.out.println(total);
}
}