Array - Introduction To Computers & Engineering
Array - Introduction To Computers & Engineering
00 Lecture 11
Arrays
• Arrays are a simple data structure
• Arrays store a set of values of the same type
– Built-in types (int, double, etc.) or
– Objects (Students, Engines, etc.)
• Arrays are part of the Java language
– Arrays are objects, not primitives like int or double.
– They are declared in the same way as other objects
int[] intArray= new int[20]; //Irregular verb
– The array object has an int data member, length, that
gives the number of elements in the array:
int aSize= intArray.length; // aSize= 20
• Each value is accessed through an index
intArray[0]= 4; intArray[1]= 77;
1
Arrays, p.2
• Array index always starts at 0, not 1
– An array with N slots has indices 0 through N-1
– intArray has elements intArray[0] through intArray
[19]
• Array lengths cannot be changed once they are
declared
• Arrays can be initialized when declared
int[] intArray= {5, 77, 4, 9, 28, 0, -9};
// new is implicit (not needed) in this case
• Arrays of numerical values are zero when
constructed
Copying arrays
2
Copying entire array
int[ ] intArray= { 5, 77, 4, 9, 28, 0, 9 };
int[ ] newArray = new int[ intArray.length ];
System.arraycopy(intArray, 0, newArray, 0, intArray.length)
intArray 5 newArray 5
77 77
4 4
9 9
28 28
0 0
9 9
3
Looping Over Arrays
• If doubleArray is a reference to array of doubles,
there are two ways to iterate over it.
– This way gives more control—you can loop over just part
of it, and you know what element (i) is being computed:
– This way is simpler but you can only iterate over the
entire array, and you dont have a loop counter (e.g., i):
4
Test Your Knowledge
3. Given this code fragment: What are the values of
the elements in array A?
int[] arrayA = new int[4]; a. unknown
int[] arrayB; b. 0,0,0,0
arrayB = arrayA;
c. 4,0,4,0
arrayB[2]=4;
d. 4,0,0,0
arrayA[0]=arrayB[2];
5
Test Your Knowledge
7. What is the output of the following program? a. value before:10
public class Test{ value after:0
public static void main ( String[] args ){ arr[0] before:10
int value = 10; arr[0] after: 0
int[] arr = {10,11,12,13}; b. value before:10
System.out.println("value before:"+value); value after:10
alterValue( value ); arr[0] before:10
System.out.println("value after:"+value); arr[0] after: 10
System.out.println("arr[0]before:"+arr[0]); c. value before:10
alterArray( arr ); value after:10
System.out.println("arr[0] after:"+arr[0]); arr[0] before:10
} arr[0] after: 0
public static void alterValue (int x ){ d. value before:10
x = 0; } value after:0
public static void alterArray (int[] a){ arr[0] before:10
a[0] = 0; } arr[0] after: 10
}
Exercise
• Create a TemperatureTest class
• Write a main() method to:
– Declare and construct an array of doubles,
called dailyTemp holding daily temperature
data
• Use an initializer list with curly braces
Mon Tue Wed Thu Fri Sat Sun
70 61 64 71 66 68 62
6
Exercise, p.2
• In class TemperatureTest, write a static method
to find average weekly temperature:
public static double average(double[] aDouble) {
// Declare a total variable, initialize it to 0
// Loop thru aDouble and add each element to the total
// Use the simple for (double d : aDouble) for loop
// Divide by the number of elements, return the answer
}
ArrayList Class
• The ArrayList class IS COMPLETELY DIFFERENT
THAN an array.
– Its a more flexible way to store data
– ArrayList can grow automatically as needed
• Has capacity that is increased when needed
• Has size() method that returns actual number of
elements in the ArrayList
– ArrayList can hold elements of different types
• As long as each is an Object (reference),
• Technically an ArrayList cant hold a basic type (int,
double, etc.)
• But, conversion of primitive to an object happens
automatically. This is called auto-boxing.
• Wrapper classes allow objects (e.g., Boolean or Double)
that hold basic types (e.g. boolean or double)
– Think airplane vs bicycle as two ways to get from A to B
• Bicycle is simple, airplane is complex, though both get you there
• Squeeze hand brake doesnt apply to plane, adjust flaps to bicycle
• So it is with arrays and ArrayLists: similar but quite different
7
ArrayLists
• ArrayList class is not in the core Java language
– It is in package java.util, which you must import:
import java.util.*; // At top of program
• ArrayLists are slightly slower than arrays
– This matters only in large numerical applications
• ArrayList class has many methods that provide
functionality beyond what arrays provide
• You can declare an ArrayList as containing
objects of a particular type. Example:
ArrayList<Point> pList = new
ArrayList<Point>( );
8
ArrayList Example
import java.awt.*; // to use Point class
import java.util.*; // to use ArrayList class
Automatic conversion of
primitives to objects
• Java has boxing and unboxing:
– When necessary, the compiler converts a primitive (e.g.,
int or double) to the corresponding object type (e.g.,
Integer or Double)
• This lets us add primitive types to an ArrayList:
ArrayList<Integer> myAList = new
ArrayList<Integer>( );
myAList.add(1); // 1 is an int; its boxed
myAList.add(3); // same as myAList.add(new
// Integer(3));
myAList.add(7);
// retrieves Integer, unboxes to int
int iValue = myAlist.get(1);
9
Test Your Knowledge
1. Which of the following statements is NOT true about
ArrayLists?
a. ArrayLists are slightly faster than arrays.
b. ArrayLists can store elements of different types.
c. ArrayLists can increase in size to store more elements.
d. ArrayLists have methods to manage their content.
10
Test Your Knowledge
3. Given the following code fragment (same as question 2):
ArrayList<String> myArrayList = new
ArrayList<String>( );
myArrayList.add("One");
myArrayList.add("Two");
myArrayList.add("Three");
myArrayList.add("Four");
a. myArrayList[3] = "Five"
b. myArrayList[4] = "Five"
c. myArrayList.set (myArrayList.indexOf("Four"), Five);
d. myArrayList.set (myArrayList.indexOf("Five"), Four);
11
Arrays and ArrayLists
Array ArrayList
• Capacity fixed at • Capacity increases as
creation data is added
• Accessed with z[i] • Accessed with z.get(i)
• Constructor: new • Constructor: new
double[30] ArrayList<Bus>();
• One data member: • No data members
z.length
• No methods • Many methods – z.size
(), z.add(), z.get()
• Slightly faster • More flexible
Exercise
• Create class CourseTest:
– import java.util.*; // 1st line in CourseTest
– In main():
• Create an ArrayList<String> students
• Add 4 students to the ArrayList:
– Amy, Bob, Cindy and David
– Add them to the ArrayList directly:
students.add("Amy");
• Write method to print elements in the ArrayList
and its size
public static void printOutArrayList(// Argument) {
// Code goes here }
• Call printOutArrayList() method from main()
– Pass the ArrayList as the argument
• Your output should be:
Amy
Bob
Cindy
David
Size: 4
12
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.