160 likes | 320 Views
ARRAYS. public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create an array of integers // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) {
E N D
ARRAYS public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create an array of integers // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } System.out.println(); } }
Array types • An array is an ordered collection or numbered list of values. The values can be primitive values, objects or even other arrays, but all of the values in an array must be of the same type. • byte b; // byte is a primitive type • Byte[] arrayOfBytes; //byte[] is an array type: array of byte • Byte[][] arrayOfArrayOfBytes; // byte[][] is another is another type: array of byte[] • Point[] points; //Point[] is an array of point objects
Creating Arrays • Use the “new” keyword • Arrays do not need to be initialized like objects do, however, so you don’t pass a list of arguments between parentheses. • BUT! You need to specify how many byte values you want it to hold. • Once an array is created, it can never grow or shrink • byte[] buffer = new byte[1024]; • string[] lines = new String[50];
Using arrays • You use square brackets to access the individual values contained in the array. The elements of an array are numbered sequentially, starting with 0. The number of an array element refers to the element. This number is often called the index, and the process of looking up a numbered value in an array is sometimes called indexing the array. • To refer to a particular element of an array, simply place the index of the desired element in square brackets after the name of the array String[] responses = new String[2]; //Create an array of two strings responses[0] = “Yes”; //Set the first element of the array responses[1] = “No”; //Set the second element of the array //Now read these array elements System.out.println(question + “(“ + response[0] + “/” + responses[1] + “ )”;
Multidimensional arrays When the elements of an array are themselves arrays, we say that the array is multi-dimensional int[][] products = new products[10][10]; • Declares a variable named products to hold an array of arrays of int • Creates a 10-element array to hold 10 arrays of int • Creates 10 more arrays, each of which is a 10-element array of int. It assigns each of these 10 new arrays to the elements of the initial array. The default value of every int element of each of these 10 new arrays is 0.
Multidimensional arrays The previous line is the same with the code below: int[][] products = new int[10][]; for (int i=0; i<10; i++) products[i] = new int[10]; The new keyword performs the additional initialisation automatically for you Float[][][] globalTemperatureData = new float[360][180][100];
Multidimensional arrays Int[][] products = { {0,0,0,0,0}, {0,1,2,3,4}, {0,2,4,6,8}, {0,3,6,9,12}, {0,4,8,12,16} }; A 5x5 multiplication array
Multidimensional arrays arraycopy() method: char[] text = “Now is the time”; char[] copy = new char[100]; System.arraycopy(text,4,copy,0,10); //move some of the text to later elements,making room for instertions System.arraycopy(copy,3,copy, 6,7)
Multidimensional arrays import java.util.Arrays; int[] intarray = new int[] {10,5,7,-3}; //An array of integers Arrays.sort(intarray); //sort it in place int pos = Arrays.binarySearch(intarray, 7); //Value 7 is found at index 2 pos = Arrays.binarySearch(intarray,12); //not found, negative return value //arrays of objects can be sorted and searched too String[] strarray = new String[] { “new”, “is”, “the”, “time”); Arrays.sort(strarray); //{“is”, “now”, “the”, “time”} //arrays equals() compares all elements of two arrays String[] clone = (String[]) strarray.clone(); boolean b1 = Arrays.equals(strarry, clone); // Yes, they are equal //arrays.fill() initialises array elements byte[] data = new byte[100]; //an empty array: elements set to 0 Arrays.fill(data, (byte) –1); //Set them all to –1 Arrays.fill(data,5,10,(byte) –2); //set elements 5,6,7,8,9 to -2
Arrays • Java has one built-in “primitive” data structure • When array is created, its capacity must be specified (with any integer expression!) and then can’t change System.out.println("Enter the number of cities >"); int ncities = Integer.valueOf(stdin.readLine()).intValue(); int rainfall[ncities]; String name[ncities]; for (int i = 0; i < cities.length; i++) { System.out.print("City " + i + " name > "); name[i] = stdin.readLine(); System.out.print("City " + i + " rainfall > "); rainfall[i] = Integer.valueOf(stdin.readLine()).intValue(); }
Input and Output streams The java.io package defines a large number of classes for reading and writing streaming, or sequential, data. The InputStream and OutputStream classes are for reading and writing streams, while the Reader and Writer classes are for reading and writing streams of characters. Streams can be nested, meaning you might read characters from a FilterReader object that reads and processes characters from an underlying Reader stream. This underlying Reader stream might read bytes from an InputStream and convert them to characters.
Read lines of input the user types import java.io.*; BufferedReader console = new Bufferedreader(new InputStreamReader(System.in)); System.out.print(“What is your name:”); String name = null; try { name = console.readLine(); } catch (IOException e) {name = “<“ + e + “>”;} System.out.println(“Hello “ + name);
Reading lines of text from a file String filename = System.getProperty(“user.home”) + File.separator + “.cshrc”; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String line; while((line = in.readLine()) !=null) { System.out.println(line);} in.close(); } catch (IOException e) { //Handle FileNootFoundException etc.. }
Print text to Output Stream try { File f = new File(homedir, “.config”); PrintWriter out = new PrintWriter(new FileWriter(f)); out.println(##Automatically generated config file. DO NOT EDIT”); out.close(); //We’re done writing } catch (IOException e) {/*Handle exceptions*/}
Not all files contain text, however. The following lines of code treat a file as a stream of bytes and read the bytes into a large array try { File f; //file to read int filesize = (int) f.length(); //figure out the file size byte[] data = new byte[filesize]; //create an array that is big enough //create a stream to read the file DataInputStream in = new DataInputStream(new FileInputStream(f)); in.readFully(data); in.close(); } catch (IOException e) {/*Handle exceptions */}
How to use stream classes from java.util.zip to compute a checksum of data and then compress the data while writing it to a file import java.io.*; import java.util.zip.*; try { File f; //file to write to byte[] data; //data to write Checksum check = new Adler32() //an object to compute a simple checksum //create a stream that writes bytes to the file f FileOutputStream fos = new FileoutputStream(f); //create a stream that compresses bytes and writes them to fos GZIPOutputStream gzos = new GZIPOutputStream(fos); //create a stream that computes a checksum on the bytes it writes to gzos CheckedOutputStream cos = new CheckedOutputStream(gzos,check); cos.write(data); //now write the data to the nested streams cos.close(); //close down the nested chain of streams long sum = check.getValue(); //obtain the computed checksum } catch (IOException e) {/* handle exceptions */}