tailieunhanh - Lecture Data structures and algorithms in Java (6th edition): Chapter 3.1 - Goodrich, Tamassia, Goldwasser
In this section, we explore a few applications of arrays - the concrete data structures introduced in lecture 1 that access their entries using integer indices. The first application we study is storing a sequence of high score entries for a video game in an array. This is representative of many applications in which a sequence of objects must be stored. | Arrays 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Arrays © 2014 Goodrich, Tamassia, Goldwasser Arrays 1 Array Definition q q An array is a sequenced collection of variables all of the same type. Each variable, or cell, in an array has an index, which uniquely refers to the value stored in that cell. The cells of an array, A, are numbered 0, 1, 2, and so on. Each value stored in an array is often called an element of that array. A 0 1 2 © 2014 Goodrich, Tamassia, Goldwasser n i Arrays 2 1 Arrays 3/18/14 Array Length and Capacity q q Since the length of an array determines the maximum number of things that can be stored in the array, we will sometimes refer to the length of an array as its capacity. In Java, the length of an array named a can be accessed using the syntax . Thus, the cells of an array, a, are numbered 0, 1, 2, and so on, up through −1, and the cell with index k can be accessed with syntax a[k]. a 0 1 2 © 2014 Goodrich, Tamassia, Goldwasser n k Arrays 3 Declaring Arrays (first way) q q The first way to create an array is to use an assignment to a literal form when initially declaring the array, using a syntax as: The elementType can be any Java base type or class name, and arrayName can be any valid Java identifier. The initial values must be of the same type as the array. © 2014 Goodrich, Tamassia, Goldwasser Arrays 4 2 Arrays 3/18/14 Declaring Arrays (second way) q The second way to create an array is to use the new operator. n q q However, because an array is not an instance of a class, we do not use a typical constructor. Instead we use the syntax: new elementType[length] length is a positive integer denoting the length of the new array. The new operator returns a reference to the new array, and typically this would be assigned to an array variable. ©
đang nạp các trang xem trước