Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Arrays (and the for-each loop) 4 11 34 15 2 1 0 214 124 2 3 4 5 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 int[] example = new int[14]; example[0]

Similar presentations


Presentation on theme: "Introduction to Arrays (and the for-each loop) 4 11 34 15 2 1 0 214 124 2 3 4 5 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 int[] example = new int[14]; example[0]"— Presentation transcript:

1 Introduction to Arrays (and the for-each loop) 4 11 34 15 2 1 0 214 124 2 3 4 5 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 int[] example = new int[14]; example[0] = 4; example[1] = 11; example[2] = 34; example[3] = 15;...

2 Plan for the next few weeks We are going to get back into Java GUIs and begin event-driven programming (making things respond to user interaction) Before we do that, though, we are going to do some work that will hopefully write better code and save us a little bit of work as we are doing our GUIs Arrays also come in handy at programming competitions like UIL and HP CodeWars, so if you are planning to go either of those make sure you pay especially close attention.

3 An array is the most basic data structure, or way of storing data. An array is a data structure with: –a fixed number of elements (a max size) –of the same type (all ints, or all JButtons, etc) All the elements in an array use the same identifier/name, but have different indices What's the point of them? 4 11 34 15 0 1 2 3

4 If you are doing a GUI containing 1000 instances of a Star class, which would you rather do? public static StarPanel extends JPanel { //declare 1000 different instance variables, each with a unique name private Star one; private Star two; … private Star ninehundrednintynine; private Star onethousand; public StarPanel() { super(); Random rand = new Random(); //instantiate each of the 1000 variables, one by one one = new Star(rand.nextInt(800),rand.nextInt(800); two = new Star(rand.nextInt(800,800); … ninehundrednintynine = new Star(rand.nextInt(800), rand.nextInt(800)); onethousand = new Star(rand.nextInt(800), rand.nextInt(800)); } public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0,0,800,800); //draw each star individually, one by one one.drawSelf(g); two.drawSelf(g); … ninehundrednintynine.drawSelf(g); onethousand.drawSelf(g); } public static StarPanel extends JPanel { private Star[] stars; //declare one instance variable to hold all 1000 stars public StarPanel() { super(); stars = new Star[1000]; //initialize array to hold 1000 Star objects Random rand = new Random(); //use loop to initialize each Star for(int i=0; i<stars.length; i++) { stars[i] = new Star(rand.nextInt(800), rand.nextInt(800)); } public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0,0,800,800); //use loop to draw each Star for(int i=0; i<stars.length; i++) { stars[i].drawSelf(g); } About 3010 lines of codeAbout 18 lines of code

5 Arrays Arrays have been around for a long time, are available in virtually every programming language, and are fairly easy to understand. Think of them as storage units you can use to put stuff in, as long as the stuff fits in the unit you have and its all the same type of stuff Arrays are not perfect, but we will get to their negative traits later and concentrate on their benefits for now. Arrays are treated like an object in Java (although they are unlike any other object in Java in that they aren't in the API, don't have non-static methods or typical constructors) Arrays can hold primitive data types (like ints or doubles) or objects (like Strings, or JButtons, or Circles)

6 Arrays and indexes In Java, an array must be given a size before you can assign elements to it. Once declared, this size cannot be changed. The starting index for arrays is always 0 (if an array contains 10 elements, the first element will be at index 0, and the last will be at index 9) To access an element in an array, you give the NAME of the array, then an [ ] containing the index of the element you want to access.

7 Declaring Arrays When you declare a normal variable, you are just giving its TYPE and its IDENTIFIER: –int x; –JButton addButton; With arrays, it works the exact same way, except for the type, you put the type of the contents of the array, then the [] to show it will be an array. –int[] intArray; –JButton[] buttons;

8 Declaring Arrays datatype[] arrayname; // the "GOOD" way...USE THIS Example: int[] myList; datatype arrayname[]; // from C, the "BAD" way Example: int myList[]; Either way works in Java, but the top way is preferred because the [] goes next to the type (making it easier to see that the variable myList is an int array) ALWAYS USE THE "GOOD" WAY...I'm just showing you the other way in case you see it somewhere and wonder what it means

9 Declaring Arrays Just like with normal variables, declaring the array doesn't put anything in memory...it just says "I'm gonna have a variable with this name and of this type". Just like with normal variables, before you can use the array, you have to instantiate it.

10 Instantiating arrays When you instantiate a variable, you are giving it a value. For primitive variables, this just means assigning it a value with the =, like x = 3; For objects, this means assigning it a value using the =, the "new" reserved word, and calling the constructor method for the object: addButton = new JButton();

11 Instantiating arrays For arrays, this means assigning it a value using the =, the "new" reserved word, and then giving the TYPE of the array and its LENGTH, enclosed in [ ]: buttons = new JButton[9]; intArray = new int[100]; Of course, the above example assumes the variables have already been declared. If they haven't been, do it in one step with: JButton[] buttons = new JButton[9]; int[] intArray = new int[100];

12 Instantiating Arrays Generic syntax: arrayName = new dataType[arraySize]; Example: myList = new int[5]; You can also declare and create an array in the same line (just like before): int[] myList = new int[5]; myList[0] is the first element in the array. myList[4] is the last element in the array. Again, you must know the length of an array before you create it. If you don't know the length, just go ahead and make a reasonable guess (or choose a large number that you don't anticipate going over).

13 Instantiating arrays When you instantiate an array, it finds contiguous space in memory for however many elements the array will contain –that's why it needs to know the type and the length, so it knows how much memory to reserve space for. When you instantiate an array, the memory locations that get reserved get initialized to the "default" for their type. –For ints, the array elements get initialized to 0 –For doubles, the array elements get initialized to 0.0 –For objects, the array elements get initialized to "null"...meaning in order to make an array of objects, you need to call a separate constructor for each element in the array

14 The Length of Arrays Once an array is created, its size is fixed and stored as a constant, public instance variable for the array. It cannot be changed. You can find its size using: arrayVariable.length For example, if you have myList.length returns 5 Note that length is a PROPERTY (an instance variable, basically), not a method. Since it is not a method, there are no parenthesis when you call it. The last element of the array is found at the index LENGTH-1 1 1 0 4 0 myList

15 Assigning elements to arrays After you declare and create an array, you can assign it values by saying: arrayName[index] = value; For instance, if I have an array of nine JButtons called buttons, then I can instantiate the first button with: buttons[0] = new JButton(); Loops are often used to initialize the values of an array. For example: for(int i=0; i<buttons.length; i++){ buttons[i] = new JButton(); buttons[i].setSize( new Dimension(50,50) ); panel.addActionListener(this); panel.add(buttons[i]); }

16 Declaring and initializing in one step – the SHORTCUT NOTATION If you want to declare, create, and assign your array all in one step, there is a shortcut you can use: char[] characters = {'a', 'b', 'c'}; JLabel[] arr = {new JLabel("1"), new JLabel("2"), new JLabel("3")}; So declare like normal, add an equal sign, open a curly brace, and list the elements (in order), with commas between each element.

17 double[] myList = {1.9, 2.9, 3.4, 3.5}; This is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5; 1.9 2.9 3.4 3.5 0 1 2 3 myList

18 Warning about shortcut If you use the curly brace notation to initialize your array, you MUST declare and initialize the array in the same statement (all one line) or else it won't work. For example, you can't say: int[] x; x = {2, 1, 3}; You must say: int[] x = {2, 1, 3};

19 Accessing elements in the array As we have seen on the previous slides, you can access an element in an array by saying: arrayName[index]; So, for instance, myList[0] returns the value of the first element in the myList array Be careful (especially when writing loops) that you always stay within the correct indices.

20 ArrayIndexOutOfBounds If you enter a negative number as the index (like myList[-2]), or a number that is equal to or greater than the length of the array (like myList[5], assuming myList has a length of 5), you will get an ArrayIndexOutOfBounds Exception. This is a very common error when dealing with arrays.

21 Loops and Arrays Because they use numbered indexes from 1 to the length of the array, loops are very often used with arrays. Simply write a for loop that starts at 0 (the first element in the array), and goes while the control variable is <arrayName.length int[] intArr = new int[10]; for(int i=0; i<intArr.length; i++) { intArr[i] = i; }

22 Examples Declare a String array of size 5 named stringArr. Declare a double array of size 300 named doubleArr. Assign the value 4.9 to the 50 th element in doubleArr. Write a loop to initially assign the value "CS" to each of the elements in stringArr

23 What is an array? What is always the starting index of an array? Write an array declaration, scores, for 100 integers. Write an array declaration, word, for 25 strings. What is ArrayIndexOutOfBounds Exception? Questions

24 The "For-Each" loop We have seen while loops, for loops, and do…while loops. Now we will discuss the last type of loop in Java: the for-each loop. The for-each loop ONLY works with collections (meaning arrays other "container" data structures)

25 Example int[] arr = {5, 2, 4, 8, 10}; int sum = 0; for(int temp : arr) sum+=temp; System.out.println(sum);

26 General syntax for(Type tmpVariableName : collectionName) { //do whatever you need to do } Note that the for-each loop is READ ONLY. This means that you can print out the elements and access their value, but you cannot modify the element inside the loop and expect it to affect the original collection. You must use a regular old for loop or while loop to do that.

27 Arrays as input parameters When you have a method that takes in a primitive data type as its input parameter, anything you do to the input parameter inside the method WILL NOT affect the original variable (you need to return a value and assign it back to the original variable to make the change) When you have a method that takes in an Object (including an array), anything you do to the input parameter will affect the original variable. So what is the result of: int[] arr = {3, 4, 1, 0, -2}; Arrays.sort(arr); for(int x : arr) { System.out.print(x + " "); }

28 Useful Stuff with Arrays: String's split method The String class has a non-static method named split that divides a String up into a String array based on a “delimiter” input parameter you give it. public String[] split(String delimiter) String x = "Hello how are you"; String[] split = x.split(" "); // use a space as the delimiter // split now contains the values {"Hello", "how", "are", "you"} with no spaces String[] split2 = x.split("o"); // use the lower-case o as the delimiter // split2 now contains the values {"Hell", " h", "w are y", "u"} with no o's

29 Useful Stuff with Arrays: Arrays class's toString method The Arrays class has a bunch of static methods you can use when working with arrays. To print out each element in an array, you could use a loop (especially a for-each loop). However, you can also System.out.println() a call to Arrays.toString(nameOfYourArray): public static String toString(int[] arr) int[] arr = {3, 1, 5, 2, 6, 3}; System.out.println(Arrays.toString(arr)); //prints out [3, 1, 5, 2, 6, 3] to the command line screen

30 Useful Stuff with Arrays: Arrays class's sort method To sort an array from least to greatest, you can call the Arrays class's static sort method. There are versions that take in an int[], double[], char[], and Object[] public static void sort(int[] a) int[] arr = {3, 1, 5, 2, 6, 3}; Arrays.sort(arr); //arr now contains the values {1, 2, 3, 3, 5, 6}

31 Potential Problems with Arrays Some people do not like using arrays because the syntax is different from other Java classes: –there isn't a int[] or double[] class in the API you can look up –they are constructed with [] instead of () like other constructor methods –they have a shortcut method that is unlike anything else –if you put an array in a System.out.println(), it doesn't print out their actual contents (you have to say System.out.println(Arrays.toString(arrayName)) instead) –Its length is a PROPERTY with no parenthesis (arrName.length) instead of a getter method like you would normally see in Java classes Another problem with arrays is that they are not dynamic: when you instantiate an array, you have to give its size, and that size cannot change. If you want to add more elements to an array that is out of room, you have to create a new, larger array and then copy over the old elements to the new one.

32 Advantages to Arrays Some people find the [] notation for accessing individual elements of an array easy to use. Each element in an array (arr[0], arr[4], arr[arr.length-1]) is treated just like any other variable would be (and can be assigned different values, printed out, or whatever) It is a fairly easy way to hold a large amount of data without declaring a ton of variables You can use loops with arrays to instantiate the individual elements or take care of repetitive actions (like adding a bunch of JButtons to a JPanel, adding ActionListeners to a bunch of JButtons, and so on)

33 For the lab: A reminder on the Random class: A Random variable is a random number generator. Once you instantiate it, you can use nameOfYourRandomVariable.nextInt(); to generate a random number. To limit the range of the number generated, put one more than the biggest number you want generated in the parenthesis of the nextInt() method, and the method will make a random number from 0 to that number. Random rand = new Random(); int x = rand.nextInt(3); //x is now either 0, 1, or 2 int y = rand.nextInt(); //y is ANY random integer value int z = rand.nextInt(100); //z is a number from 0 to 99


Download ppt "Introduction to Arrays (and the for-each loop) 4 11 34 15 2 1 0 214 124 2 3 4 5 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 int[] example = new int[14]; example[0]"

Similar presentations


Ads by Google