SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Computer Programming
                                                            Chapter 6 : Array and ArrayList




                                            Atit Patumvan
                            Faculty of Management and Information Sciences
                                          Naresuna University




Tuesday, August 2, 2011
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



                                                                                     อาเรย์ (Array)


            •         เป็นโครงสร้างพื้นฐานในการจัดเก็บชุดข้อมูล

            •         เป็นการจัดเก็บชุดข้อมูลที่มีชนิดเดียวกันเข้าไว้ด้วยกัน

            •         ข้อมูลแต่ละตัวเรียกว่า อิลิเมนต์ (element) หรือ เซลล์ (cell)

            •         การอ้างอิงถึงข้อมูลที่อยู่ในแต่ละอิลิเมนต์ จะใช้ตัวชี้ที่เรียกว่า อิน
                      เด็กซ์ (index) หรือ ซับสคริปต์ (subscript)

                    •        การอ้างอิงถึงข้อมูลจะต้องอยู่ใน เครื่องหมาย bracket ʻ[ ]ʼ




Atit Patumvan, Faculty of Management and Information Sciences, Naresuan University
Tuesday, August 2, 2011
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



                                                                                 อาร์เรย์ (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



                                          การประกาศอาเรย์ (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



                                          การประกาศอาเรย์ (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



                                                                             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



                          ข้อผิดพลาดที่เกิดขึ้นเป็นประจํา (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



                                                                     การเติมสมาชิก (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



                               การหาผลรวมและค่าเฉลี่ย (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



                     หาค่ามากและหาค่าน้อย (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



                     หาค่ามากและหาค่าน้อย (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



                                                      ค้นหาสมาชิกของอาเรย์ (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



                                                                          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



                                                                                     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



                                                              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



                                         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



                                                               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



                                                                                     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



                                                  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



                                                               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



                                                                              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



                                                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



                                 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

Weitere ähnliche Inhalte

Was ist angesagt?

Image Processing 1
Image Processing 1Image Processing 1
Image Processing 1
jainatin
 
DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...
DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...
DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...
cscpconf
 
Perceptron Slides
Perceptron SlidesPerceptron Slides
Perceptron Slides
ESCOM
 
Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
Pierre Vigneras
 
ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...
ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...
ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...
csandit
 
Adaptive blind multiuser detection under impulsive noise using principal comp...
Adaptive blind multiuser detection under impulsive noise using principal comp...Adaptive blind multiuser detection under impulsive noise using principal comp...
Adaptive blind multiuser detection under impulsive noise using principal comp...
csandit
 
Latent factor models for Collaborative Filtering
Latent factor models for Collaborative FilteringLatent factor models for Collaborative Filtering
Latent factor models for Collaborative Filtering
sscdotopen
 

Was ist angesagt? (20)

Image Processing 1
Image Processing 1Image Processing 1
Image Processing 1
 
Neural network
Neural networkNeural network
Neural network
 
DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...
DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...
DESIGN AND IMPLEMENTATION OF BINARY NEURAL NETWORK LEARNING WITH FUZZY CLUSTE...
 
Chtp405
Chtp405Chtp405
Chtp405
 
Polikar10missing
Polikar10missingPolikar10missing
Polikar10missing
 
Neural network
Neural networkNeural network
Neural network
 
Neural network
Neural networkNeural network
Neural network
 
Bayesian Generalization Error and Real Log Canonical Threshold in Non-negativ...
Bayesian Generalization Error and Real Log Canonical Threshold in Non-negativ...Bayesian Generalization Error and Real Log Canonical Threshold in Non-negativ...
Bayesian Generalization Error and Real Log Canonical Threshold in Non-negativ...
 
Perceptron Slides
Perceptron SlidesPerceptron Slides
Perceptron Slides
 
Feed forward neural network for sine
Feed forward neural network for sineFeed forward neural network for sine
Feed forward neural network for sine
 
Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
 
Artificial neural networks
Artificial neural networks Artificial neural networks
Artificial neural networks
 
A Framework for Cross-media Information Management
A Framework for Cross-media Information ManagementA Framework for Cross-media Information Management
A Framework for Cross-media Information Management
 
Matrix Factorization
Matrix FactorizationMatrix Factorization
Matrix Factorization
 
Why not scoping Subject Identifiers?
Why not scoping Subject Identifiers?Why not scoping Subject Identifiers?
Why not scoping Subject Identifiers?
 
Dr. kiani artificial neural network lecture 1
Dr. kiani artificial neural network lecture 1Dr. kiani artificial neural network lecture 1
Dr. kiani artificial neural network lecture 1
 
ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...
ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...
ADAPTIVE BLIND MULTIUSER DETECTION UNDER IMPULSIVE NOISE USING PRINCIPAL COMP...
 
Adaptive blind multiuser detection under impulsive noise using principal comp...
Adaptive blind multiuser detection under impulsive noise using principal comp...Adaptive blind multiuser detection under impulsive noise using principal comp...
Adaptive blind multiuser detection under impulsive noise using principal comp...
 
Latent factor models for Collaborative Filtering
Latent factor models for Collaborative FilteringLatent factor models for Collaborative Filtering
Latent factor models for Collaborative Filtering
 
Ann by rutul mehta
Ann by rutul mehtaAnn by rutul mehta
Ann by rutul mehta
 

Andere mochten auch (15)

Apresentação2
Apresentação2Apresentação2
Apresentação2
 
Urbanwatersecurity
UrbanwatersecurityUrbanwatersecurity
Urbanwatersecurity
 
A current mode quadrature oscillator using cdta
A current mode quadrature oscillator using cdtaA current mode quadrature oscillator using cdta
A current mode quadrature oscillator using cdta
 
Purdue_Impact_Summer2008pg7
Purdue_Impact_Summer2008pg7Purdue_Impact_Summer2008pg7
Purdue_Impact_Summer2008pg7
 
Carreras de la muerte dama
Carreras de la muerte damaCarreras de la muerte dama
Carreras de la muerte dama
 
Proyecto de innovación
Proyecto de innovaciónProyecto de innovación
Proyecto de innovación
 
FINLAY_A_KEITH_CV
FINLAY_A_KEITH_CVFINLAY_A_KEITH_CV
FINLAY_A_KEITH_CV
 
Gbia
GbiaGbia
Gbia
 
Probabilidad
ProbabilidadProbabilidad
Probabilidad
 
Concussion Protocol
Concussion ProtocolConcussion Protocol
Concussion Protocol
 
Demineralized Bone Matrix
Demineralized Bone MatrixDemineralized Bone Matrix
Demineralized Bone Matrix
 
uc
ucuc
uc
 
poster_template_M&E_S15(1)
poster_template_M&E_S15(1)poster_template_M&E_S15(1)
poster_template_M&E_S15(1)
 
Shoulder Instability & Labral Repairs (SLAP Repairs)
Shoulder Instability & Labral Repairs (SLAP Repairs)Shoulder Instability & Labral Repairs (SLAP Repairs)
Shoulder Instability & Labral Repairs (SLAP Repairs)
 
อัลบั้มรูปบรรยากาศบ้านฉัน
อัลบั้มรูปบรรยากาศบ้านฉันอัลบั้มรูปบรรยากาศบ้านฉัน
อัลบั้มรูปบรรยากาศบ้านฉัน
 

Ähnlich wie Computer Programming Chapter 6 : Array and ArrayList

Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
SANTOSH RATH
 

Ähnlich wie Computer Programming Chapter 6 : Array and ArrayList (20)

Arrays
ArraysArrays
Arrays
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
OOP Chapter 3: Classes, Objects and Methods
OOP Chapter 3: Classes, Objects and MethodsOOP Chapter 3: Classes, Objects and Methods
OOP Chapter 3: Classes, Objects and Methods
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Introduction to Exploratory Data Analysis with the sci-analysis Python Package
Introduction to Exploratory Data Analysis with the sci-analysis Python PackageIntroduction to Exploratory Data Analysis with the sci-analysis Python Package
Introduction to Exploratory Data Analysis with the sci-analysis Python Package
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
 
Unit 3
Unit 3 Unit 3
Unit 3
 
20 bayes learning
20 bayes learning20 bayes learning
20 bayes learning
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
 
Java cơ bản java co ban
Java cơ bản java co ban Java cơ bản java co ban
Java cơ bản java co ban
 
Implement principal component analysis (PCA) in python from scratch
Implement principal component analysis (PCA) in python from scratchImplement principal component analysis (PCA) in python from scratch
Implement principal component analysis (PCA) in python from scratch
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
IRJET- Unabridged Review of Supervised Machine Learning Regression and Classi...
IRJET- Unabridged Review of Supervised Machine Learning Regression and Classi...IRJET- Unabridged Review of Supervised Machine Learning Regression and Classi...
IRJET- Unabridged Review of Supervised Machine Learning Regression and Classi...
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
BIT211_2.pdf
BIT211_2.pdfBIT211_2.pdf
BIT211_2.pdf
 
OOP Chapter 7 : More on Classes
OOP Chapter 7 : More on ClassesOOP Chapter 7 : More on Classes
OOP Chapter 7 : More on Classes
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
 

Mehr von Atit Patumvan

แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ตแบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
Atit Patumvan
 
Chapter 1 mathmatics tools
Chapter 1 mathmatics toolsChapter 1 mathmatics tools
Chapter 1 mathmatics tools
Atit Patumvan
 
Computer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : MethodsComputer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : Methods
Atit Patumvan
 
Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops
Atit Patumvan
 
Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)
Atit Patumvan
 

Mehr von Atit Patumvan (20)

Iot for smart agriculture
Iot for smart agricultureIot for smart agriculture
Iot for smart agriculture
 
An Overview of eZee Burrp! (Philus Limited)
An Overview of eZee Burrp! (Philus Limited)An Overview of eZee Burrp! (Philus Limited)
An Overview of eZee Burrp! (Philus Limited)
 
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ตแบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
 
Chapter 1 mathmatics tools
Chapter 1 mathmatics toolsChapter 1 mathmatics tools
Chapter 1 mathmatics tools
 
Chapter 1 mathmatics tools
Chapter 1 mathmatics toolsChapter 1 mathmatics tools
Chapter 1 mathmatics tools
 
รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556
รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556
รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556
 
Chapter 0 introduction to theory of computation
Chapter 0 introduction to theory of computationChapter 0 introduction to theory of computation
Chapter 0 introduction to theory of computation
 
Media literacy
Media literacyMedia literacy
Media literacy
 
Chapter 01 mathmatics tools (slide)
Chapter 01 mathmatics tools (slide)Chapter 01 mathmatics tools (slide)
Chapter 01 mathmatics tools (slide)
 
การบริหารเชิงคุณภาพ ชุดที่ 8
การบริหารเชิงคุณภาพ ชุดที่ 8การบริหารเชิงคุณภาพ ชุดที่ 8
การบริหารเชิงคุณภาพ ชุดที่ 8
 
การบริหารเชิงคุณภาพ ชุดที่ 7
การบริหารเชิงคุณภาพ ชุดที่ 7การบริหารเชิงคุณภาพ ชุดที่ 7
การบริหารเชิงคุณภาพ ชุดที่ 7
 
การบริหารเชิงคุณภาพ ชุดที่ 6
การบริหารเชิงคุณภาพ ชุดที่ 6การบริหารเชิงคุณภาพ ชุดที่ 6
การบริหารเชิงคุณภาพ ชุดที่ 6
 
Computer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : MethodsComputer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : Methods
 
Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops
 
Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)
 
การบริหารเชิงคุณภาพ ชุดที่ 5
การบริหารเชิงคุณภาพ ชุดที่ 5การบริหารเชิงคุณภาพ ชุดที่ 5
การบริหารเชิงคุณภาพ ชุดที่ 5
 
การบริหารเชิงคุณภาพ ชุดที่ 4
การบริหารเชิงคุณภาพ ชุดที่ 4การบริหารเชิงคุณภาพ ชุดที่ 4
การบริหารเชิงคุณภาพ ชุดที่ 4
 
การบริหารเชิงคุณภาพ ชุดที่ 3
การบริหารเชิงคุณภาพ ชุดที่ 3การบริหารเชิงคุณภาพ ชุดที่ 3
การบริหารเชิงคุณภาพ ชุดที่ 3
 
การบริหารเชิงคุณภาพ ชุดที่ 2
การบริหารเชิงคุณภาพ ชุดที่ 2การบริหารเชิงคุณภาพ ชุดที่ 2
การบริหารเชิงคุณภาพ ชุดที่ 2
 
Computer Programming: Chapter 1
Computer Programming: Chapter 1Computer Programming: Chapter 1
Computer Programming: Chapter 1
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Kürzlich hochgeladen (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

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