1. Trang chủ
  2. » Giáo án - Bài giảng

Chapter 5 Arrays

28 453 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 28
Dung lượng 559,5 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Using the array• If a is an array, to process all elements in a, using: • See BasicArray.java, page 322... Sorting elements in an array• See Java Software Solution page 339349  selecti

Trang 1

Chapter 5

Trang 3

values of the same type

 Array indices are zero-based

 Example: scores[5] returns the 5 th value in the array

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91

scores

The entire array

has a single name

Each value has an index

Trang 4

Declaring an array

 int[] scores = new int[100];

• an array that can hold 100 integers

 String[] names;

names = new names[20];

• an array that can hold 20 String objects

values at the same time

 int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };

 char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

DataType[] arrayName = new DataType[ size ] ;

DataType[] arrayName; // only declares the variable

arrayName = new DataType[ size ] ;

See ebook page 328 for other syntax

Trang 5

Using the array

If a is an array, to process all elements in a, using:

See BasicArray.java, page 322 Modify the program to input values

for (int i=0; i < a.length; i++)

Trang 6

Bounds checking

cannot access indexes outside this limit

 The Java interpreter throws an exception named

ArrayIndexOutOfBoundsException if an array index is out of bounds

• This is called automatic bounds checking

for (int i=0; i <= codes.length; i++)

codes[i] = i*50 + epsilon;

problem

Trang 7

Array as Parameters

method

passed as a parameter, a copy of the reference to the original array is passed (they become aliases of each other)

 Therefore, changing an array element within the method changes the original

see Mang1Chieu.java

Trang 9

Array of objects

 String[] words = new String [10];

• words object stores 10 references to String objects

 Rectangle[] rects = new Rectangle [5];

• rects object stores 5 references to Rectangle objects

separately

Trang 10

Array of String

- - -

-• At this point, the following reference would throw a

System.out.println (words[0]);

String[] words = new String [10];

Trang 11

Array of String (cont.)

-"loyalty"

"honor"

String [] words = new String[10];

Words[0] = new String(“friendship”);

Words[1] = new String(“loyalty”);

Words[2] = new String(“honor”);

Trang 12

Array of Rectangle

After some Rectangle objects are created and stored in the array:

Demo: Write method to input and output array of rectangle

(5,4) rects

-

-(7,3) (100,50)

rects[0] = new HinhChuNhat( 5,4 );

rects[1] = new HinhChuNhat( 7,3 );

rects[2] = new HinhChuNhat( 100,50 );

Rectangle[] rects = new Rectangle [5];

Trang 13

Example: Array of objects

collection of CD objects

 See CD.java (page 340)

 See CDCollection.java (page 337)

 See Tunes.java (page 335)

Trang 14

Example: Array of objects

cost : double, tracks : int) : void + toString() : String

Trang 16

Sorting elements in an array

See Java Software Solution (page 339349)

 selection sort (page 341)

 insertion sort (page 345)

To sort an array of numbers, you can use one of the sort

methods in the Arrays class (using a tuned QuickSort algorithm)

 Arrays.sort(type[] a): a is an array of type int, long, short,

char, byte, float or double

 Example:

• int[] a = new int[10000];

Arrays.sort(a);

• How to sort an array of objects by using sort method

in the Arrays class?

Trang 17

Sorting an array of objects

Arrays class, the objects must belong to classes that implement the Comparable interface

 Example: you want to sort an array of Rectangle order

by area ascending

public class Rectangle implements Comparable<Rectangle> {

… public int compareTo (Rectangle other) {

if (getArea() < other.getArea()) return -1;

else if (getArea() > other.getArea()) return 1; return 1;

} }

Trang 18

Searching value in the array

binarySearch method in the Arrays class

 int Arrays.binarySearch( type[] a, type v )

• a: a sorted array of type int, long, short, char, byte, float or

double

• v: a value of the same type as the elements of a

• If it is found, its index is returned

• Otherwise, a negative value is returned

Trang 20

Two-Dimensional Arrays

A two-dimensional array can be thought of as a table of elements, with rows and columns

A two-dimensional array is declared by specifying the size of each dimension separately:

int[][] scores = new int[12][50];

A array element is referenced using two index values:

value = scores[3][6];

two dimensions

Trang 21

int[][] table = new int [5][10];

for (int row=0; row < table.length; row++)

for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col;

for (int row=0; row < table.length; row++)

{

for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println();

}

}

}

Trang 23

Why do we use ArrayList class?

Problem:

 In C/C++, you have to fix the sizes of all arrays at compile time

• forces users into uncomfortable

 In Java, the situation is much better You can set the size

of an array at run time

int size= ;

Rectangle[] rects = new Rectangle[size];

• once you set the array size, you cannot change it easily

Instead, the easiest way in Java to deal with this

common situation is to use the ArrayList class

The ArrayList class is similar to an array, but it

automatically adjusts its capacity as you add and

remove elements, without your needing to write any

code

Trang 24

Declaring an ArrayList object

Syntax:

As of JDK 5.0, ArrayList is a generic class with a type

parameter, so you must to specify the type of the

element objects that the array list holds

 ArrayList<Rectangle> rects = new

ArrayList<Rectangle>();

 ArrayList<String> alName = new ArrayList<String>();

 ArrayList<Integer> alName = new ArrayList<Integer>();

The ArrayList class is part of the java.util

package

Some methods of the ArrayList class: see next…

Trang 25

Methods of the ArrayList

• ArrayList<T>()

 constructor: creates an empty array list

• boolean add(T obj)

 appends an element at the end of the array list Always

returns true

• void add (int index, T obj)

 inserts the specified object into this list at the specified index

• void clear()

 removes all elements from this list

• T remove (int index)

 removes the element at the specified index in this list

and returns it

Trang 26

Methods of the ArrayList (cont.)

• void set(int index, T obj)

 puts a value in the array list at the specified index,

overwriting the previous contents

• T get(int index)

 gets the value stored at a specified index

• int indexOf(T obj)

 returns the index of the first occurrence of the specified object

• boolean contains(T obj)

 returns true if this list contains the specified object

Trang 28

Accessing ArrayList elements

 Example: suppose to have an ArrayList named rects

for (int i=0; i<rects.size(); i++)

{

Rectangle h = (Rectangle) rects.get(i);

System.out.println(“Area: ” + h getArea());

System.out.println(“Perimeter: ” + h getPerimeter()); }

Ngày đăng: 13/05/2014, 10:42

Xem thêm

TỪ KHÓA LIÊN QUAN