Computer Programming Chapter 6 : Array and ArrayList
1. Computer Programming
Chapter 6 : Array and ArrayList
Atit Patumvan
Faculty of Management and Information Sciences
Naresuna University
Tuesday, August 2, 2011
2. 2
Collections
• Collection is a group of objects contained in a single
element.
• Example of collection include an array of integer, a vector
of string, or a hash map of vehicles.
• The Java Collection Framework is a unified set of classes
and interfaces defined in the java.util package for storing
collections.
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
3. 3
อาเรย์ (Array)
• เป็นโครงสร้างพื้นฐานในการจัดเก็บชุดข้อมูล
• เป็นการจัดเก็บชุดข้อมูลที่มีชนิดเดียวกันเข้าไว้ด้วยกัน
• ข้อมูลแต่ละตัวเรียกว่า อิลิเมนต์ (element) หรือ เซลล์ (cell)
• การอ้างอิงถึงข้อมูลที่อยู่ในแต่ละอิลิเมนต์ จะใช้ตัวชี้ที่เรียกว่า อิน
เด็กซ์ (index) หรือ ซับสคริปต์ (subscript)
• การอ้างอิงถึงข้อมูลจะต้องอยู่ใน เครื่องหมาย bracket ʻ[ ]ʼ
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
4. 4
อาร์เรย์ (Array)
01: public class PoorScoreProcessing {
02:
03: public static void main(String[] args) {
alice_score 04: int alice_score = 18;
05: int bob_score = 20;
18 06: int carry_score = 35;
07: int dart_score = 21;
int 08: double average_score = averageScore(
bob_score
09: alice_score,
20 10: bob_score,
11: carry_score,
int 12: dart_score);
carry_score 13: System.out.println("Average score is " + average_score);
14: }
35 15:
16: public static double averageScore(
int 17: int s1,
dart_score 18: int s2,
19: int s3,
21 20: int s4) {
21: int sum = s1 + s2 + s3 + s4;
int 22: double avr = sum / 4.0;
23: return avr;
24:
25: }
26: }
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
5. 5
อาร์เรย์ (Array)
score int
18 20 35 21
01: public class ScoreProcessing {
02:
03: public static void main(String[] args) {
04: int[] score = {18, 20, 35, 21};
05:
06: double average_score = averageScore(score);
07: System.out.println("Average score is " + average_score);
08: }
09:
10: public static double averageScore(int[] scores) {
11: int sum = 0;
12: for (int score : scores) {
13: sum += score;
14: }
15: double avr = sum / (double) scores.length;
16: return avr;
17:
18: }
19: }
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
6. 6
การประกาศอาเรย์ (Array Declaration)
Name of array variable length
double [] data = new double [10];
type of array variable element type
data
double double double double double double double double double double
double [ ]
data @AB1F245H
double[ ]
double[ ]@AB1F245H
double double double double double double double double double double
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
7. 7
การประกาศอาเรย์ (Array Declaration)
int [ ] numbers = new int [10]
final int LENGTH = 10;
int [ ] numbers = new int [ LENGTH ];
int length = in.nextInt();
int [ ] numbers = new int [ length ];
int [ ] numbers = { 0, 1, 4, 9, 16};
String [ ] friends = {“Alice”, “Bob”, “Carry”};
Person alice = new Person();
Person bob = new Person();
Person carry = new Person();
Person [ ] persons = {alice, bob, carry};
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
8. 8
Array Reference
01: public class ArrayReference {
02:
03: public static void main(String[] args) {
04: int[] array1 = {1, 2, 3, 4, 5};
05: int[] array2 = array1;
06: array1[0] = 7;
07: System.out.println(array2[0]);
08: }
09: }
int[ ]@AB1F245H
array1 @AB1F245H
int[ ] 1 2 3 4 5
int[0] int[1] int[2] int[3] int[4]
array2 @AB1F245H
int[ ]
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
9. 9
ข้อผิดพลาดที่เกิดขึ้นเป็นประจํา (Common Errors)
• อ้างอิงอินเด็กซ์ผิดพลาด (Bound Error)
01: public class ArrayError1 {
02:
03: public static void main(String[] args) {
04: int[ ] data = new int[10];
05: data[10] = 5.4; // Error: data has 10 elements with index value 0 to 9
06: }
07:}
• ไม่ได้จองพื้นที่ในหน่วยความจํา (Initialized Error)
01: public class ArrayError2 {
02:
03: public static void main(String[] args) {
04: int[ ] data;
05: data[0] = 5.4; // Error: data not initialized
06: }
07:}
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
10. 10
การเติมสมาชิก (filling)
01: public class FillingArray {
02:
03: public static void main(String[] args) {
04: int[] data = new int[5];
05: for (int index = 0; index < data.length; index++) {
06: data[index] = index * index;
07: }
08: }
09:}
0 1 4 9 16
data
int[0] int[1] int[2] int[3] int[4]
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
11. 11
การหาผลรวมและค่าเฉลี่ย (sum and average)
0 1 4 9 16
data
01: public class SumAndAverage { int[0] int[1] int[2] int[3] int[4]
02:
03: public static void main(String[] args) {
04: int[] data = new int[5];
05: for (int index = 0; index < data.length; index++) {
06: data[index] = index * index;
07: }
08:
09: double total = 0;
10: for (int element : data) {
11: total = total + element;
12: }
13: double average = 0;
14: if (data.length > 0) {
15: average = total / (double) data.length;
16: }
17: System.out.println("total: " + total);
18: System.out.println("average: " + average);
19: }
20:}
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
12. 12
หาค่ามากและหาค่าน้อย (maximum and minimum)
01: public class MinMax {
02:
03: public static void main(String[] args) {
04: int[] data = new int[5];
05: for (int index = 0; index < data.length; index++) {
06: data[index] = (int) (Math.random()*100);
07: System.out.println("data["+index+"]="+data[index]);
08: }
09:
10: int min = data[0];
11: int max = data[0];
12: for (int index = 1; index < data.length; index++) {
13:
14: if(min > data[index]){
15: min = data[index]; data[0]=16
16: } data[1]=37
17: data[2]=11
18: if(max < data[index]){
data[3]=32
19: max = data[index];
20: } data[4]=92
21: } min: 11
22: max: 92
23: System.out.println("min: " + min);
24: System.out.println("max: " + max);
25: }
26:}
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
13. 13
หาค่ามากและหาค่าน้อย (maximum and minimum)
01: public class MinMax {
02:
03: public static void main(String[] args) {
04: int[] data = new int[5];
05: for (int index = 0; index < data.length; index++) {
06: data[index] = (int) (Math.random()*100);
07: System.out.println("data["+index+"]="+data[index]);
08: }
09:
10: int min = data[0];
11: int max = data[0];
12: for (int index = 1; index < data.length; index++) {
13:
14: if(min > data[index]){ data[0]=16
15: min = data[index];
16: }
data[1]=37
17: data[2]=11
18: if(max < data[index]){ data[3]=32
19: max = data[index]; data[4]=92
20: }
21: } min: 11
22: max: 92
23: System.out.println("min: " + min);
24: System.out.println("max: " + max);
25: }
26:}
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
14. 14
ค้นหาสมาชิกของอาเรย์ (Search)
01: public class Search {
02:
03: public static void main(String[] args) {
04: int[] data = new int[5]; data[0]=7
05: for (int index = 0; index < data.length; index++) {
06: data[index] = (int) (Math.random()*10); data[1]=4
07: System.out.println("data["+index+"]="+data[index]); data[2]=3
08: } data[3]=6
09: int searchValue = 5;
10: int position = 0;
data[4]=2
11: boolean found = false; search value = 5
12: while(position < data.length && !found){ Not found
13: if(data[position]== searchValue){
14: found = true;
15: } else { data[0]=1
16: position++;
data[1]=3
17: }
18: } data[2]=5
19: System.out.println("search value = " + searchValue); data[3]=8
20: if(found){ data[4]=4
21: System.out.println("Found at "+position );
22: } else {
search value = 5
23: System.out.println("Not found"); Found at 2
24: }
25: }
26:}
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
15. 15
Insert an Element
01: import java.util.Arrays;
02:
03: public class ArrayInsertElement {
04:
05: public static void insertElement(int[] data, int index, int value) {
06:
07: for (int position = data.length - 2; position >= index; position--) {
08: data[position + 1] = data[position];
09: }
10: data[index] = value;
11: }
12:
13: public static void main(String[] args) {
14: int[] data = new int[5];
15: for (int index = 0; index < data.length; index++) {
16: data[index] = (int) (Math.random() * 10);
17: System.out.println("data[" + index + "]=" + data[index]);
18: }
19: data[0]=7
20: System.out.println("Before :" + Arrays.toString(data)); data[1]=3
21: insertElement(data, 1, 99); data[2]=9
22: System.out.println("After :" + Arrays.toString(data)); data[3]=0
23: } data[4]=2
Before :[7, 3, 9, 0, 2]
24: }
After :[7, 99, 3, 9, 0]
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
16. 16
Copy Array
01: import java.util.Arrays;
02:
03: public class ArrayCopy {
04:
05: public static void main(String[] args) {
06: int[] data1 = new int[5];
07: for (int index = 0; index < data1.length; index++) {
08: data1[index] = (int) (Math.random() * 10);
09: System.out.println("data[" + index + "]=" + data1[index]);
10: }
11:
12: System.out.println("data1[] =" + Arrays.toString(data1));
13: int[] data2 = Arrays.copyOf(data1, data1.length);
14: System.out.println("data2[] =" + Arrays.toString(data2));
15: }
16: }
data[0]=9
data[1]=2
data[2]=6
data[3]=7
data[4]=3
data1[] =[9, 2, 6, 7, 3]
data2[] =[9, 2, 6, 7, 3]
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
17. 17
Two Dimensional Arrays
Winter Olympics 206: Figure Skating Medal Counts
0 0 1
Gold Silver Bronze counts
Canada 0 0 1 0 1 1
China 0 1 1
Japan 1 0 0
1 0 0
Russia 3 0 0 3 0 0
number of rows
Name of array variable int [ ] [ ] counts = {
{0,0,1},
{0,1,1},
{1,0,0},
int [ ][ ] data = new int [4][3]; {3,0,0}
};
type of array variable number of columns
element type
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
18. 18
Accessing Two-Dimensional Arrays
01: public class MultiDimensionalArrays {
02:
03: public static final int COUNTRIES = 4;
04: public static final int MEDALS = 3;
05: 0 0 1
06: public static void main(String[] args) { 0 1 1
07: int[][] counts = {
08: {0, 0, 1},
1 0 0
09: {0, 1, 1}, 3 0 0
10: {1, 0, 0},
11: {3, 0, 0}
12: };
13: for (int i = 0; i < COUNTRIES; i++) {
14: for (int j = 0; j < MEDALS; j++) {
15: System.out.printf("%8d", counts[i][j]);
16: }
17: System.out.println();
18: }
19: }
20: }
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
19. 19
Using Objects in Arrays
01: import java.util.Arrays; 01: public class ModalCount {
02: 02:
03: public class Country { 03: public static void main(String[] args) {
04: public static final int GOLD = 0; 04: Country[] countries = new Country[4];
05: public static final int SILVER = 0; 05: countries[0] = new Country("Canada");
06: public static final int BRONZE = 0; 06: countries[1] = new Country("China");
07: 07: countries[2] = new Country("Japan");
08: private String name; 08: countries[3] = new Country("Russia");
09: private int [] counts = new int [3]; 09:
10: 10: countries[0].setModal(Country.BRONZE, 1);
11: public Country(String name){ 11: countries[1].setModal(Country.SILVER, 1);
12: this.name = name; 12: countries[1].setModal(Country.BRONZE, 1);
13: } 13: countries[2].setModal(Country.GOLD, 1);
14: 14: countries[3].setModal(Country.GOLD, 3);
15: public void setModal(int type, int number){ 15:
16: counts[type]=number; 16: System.out.println(countries[0]);
17: } 17: System.out.println(countries[1]);
18: 18: System.out.println(countries[2]);
19: @Override 19: System.out.println(countries[3]);
20: public String toString(){ 20: }
21: return name +"="+ Arrays.toString(counts); 21: }
22: }
23: }
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
20. 20
ArrayList
• ArrayList is a class in the standard Java libraries
• ArrayList is an object that can grow and shrink while your
program is running
• An ArrayList serves the same purpose as an array, except
that an ArrayList can change length while the program is
running
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
21. 21
Declaring and Using Array List
Name of number of rows
array list variable
ArrayList <String> friends = new ArrayList<String>();
type of element type
array list variable
friends.add(“Alice”);
String name = friends.get(i);
friends.set(i, “Bob”);
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
22. 22
Working with Array List
01: import java.util.ArrayList;
02:
+ Person 03: public class AddingElements {
04:
- name : String 05: public static void main(String[] args) {
06: ArrayList<Person> friends = new ArrayList<Person>();
07: friends.add(new Person("Alice"));
+ Person(String) 08: friends.add(new Person("Bob"));
+ getName() : String 09:
+ setName(String) : void 10: System.out.println("Numbers of friends : " + friends.size());
11:
12: Person firstPerson = friends.get(0);
13: System.out.println("Name of first friend is "+
01: public class Person { firstPerson.getName());
02: 14:
03: private String name; 15: friends.set(1, new Person("Carry"));
04: 16: Person secondPerson = friends.get(1);
05: public Person(String name) { 17: System.out.println("Name of second friend is " +
06: this.name = name; secondPerson.getName());
07: } 18:
08: 19: friends.remove(0);
09: public String getName() { 20: firstPerson = friends.get(0);
10: return name; 21: System.out.println("Name of first friend is " +
11: } firstPerson.getName());
12: 22: }
13: public void setName(String name) { 23: }
14: this.name = name;
15: } Numbers of friends : 2
16: } Name of first friend is Alice
Name of second friend is Carry
Name of first friend is Carry
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
23. 23
Copy Array List
01: import java.util.ArrayList;
+ Person 02:
03: public class CopyingArray {
- name : String 04:
05: public static void main(String[] args) {
06: ArrayList<Person> friends1 = new ArrayList <Person>();
+ Person(String) 07: friends1.add(new Person("Alice"));
+ getName() : String 08: friends1.add(new Person("Bob"));
+ setName(String) : void 09:
10: ArrayList<Person> friends2 = (ArrayList) friends1.clone();
11:
12: friends1.add(0, new Person("Carry"));
01: public class Person { 13:
02: 14: Person firstPerson = friends1.get(0);
03: private String name; 15: System.out.println(firstPerson.getName());
04: 16:
05: public Person(String name) { 17: firstPerson = friends2.get(0);
06: this.name = name; 18: System.out.println(firstPerson.getName());
07: } 19:
08: 20: }
09: public String getName() { 21: }
10: return name;
11: }
12:
13: public void setName(String name) {
14: this.name = name;
15: }
16: }
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
24. 24
Wrapper Class and Auto-boxing
Primitive Type Wrapper Class 01: import java.util.ArrayList;
byte Byte 02:
03: public class Wrapper {
boolean Boolean
04:
char Char 05: public static void main(String[] args) {
double Double 06: Double wrapper = 29.35;
07: double x = wrapper;
float Float
08:
int Integer 09: ArrayList<Double> data = new ArrayList<Double>();
long Long 10: data.add(29.35);
short Short 11: double y = data.get(0);
12: }
13: }
Double@AB1F245H
wrapper @AB1F245H value 29.35
Double
Double
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
25. 25
Compare Array and Array List Operation
Operation Array ArrayList
Get an element. x = data[4] x = data.get(4)
Replace an element. data[4] = 35; data.set(4, 35);
Number of elements. data.length data.size();
Number of filled elements. - data.size();
Remove an element. - data.remove(4);
Add an element, growing the
- data.add(35);
collection.
Initializing a collection int[] data = { 1, 4, 9}; -
Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011