Popular in Course
verified elite notetaker
Popular in Department
This 6 page Reader was uploaded by Dustin Luu on Monday August 18, 2014. The Reader belongs to a course at a university taught by a professor in Fall. Since its upload, it has received 374 views.
Reviews for 328479784Chapter12Arrays.pdf
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 08/18/14
Chapter 12 Arrays 122 One Dimensional Arrays 0 You can have an array of elements of any type use empty brackets after the type name to indicate that a variable refers to an array Ex sometype someName nt scores Arrays in Java are similar to objects 0 First you need to declare an arraytype variable then create the array using the new operator Ex int scores new int10 scores declares an array of integers and the 3910 creates that array with 10 elements Heres an array consisting 5000 strings and 16 colors ExString words new String5000 Coor colors new coor16 When an array is created its elements are initialized to default values Numeric elements are initialized to 0 boolean to false lf array elements are of a class type then the array contains references to objects of that type these are initialized to null Another way to declare and create an array is to list explicitly between braces the values of all its elements The new operator is not used in this form Exint scores 95 97 79 99 100 creates an array of five integers String names quotVikas quotLarisa quotNick creates an array of three strings Coor rainbowCoors creates an array of seven colors CoorRED CoorORANGE CoorYELLOW CoorGREEN CoorCYAN coorBLUE CoorMAGENTA In Java onve an array is declared an initialized either with the new operator or with a list of values it is not possible to change its size To increase the size you need to create a larger array which requires scrapping the old one and making a new one but bigger A program can access individual elements of an array using indices also called subscripts An index is an integer value placed in square brackets after the array name to identify the element The elements of an array are numbered starting from 0 declares an array of 100 interger elements final int MAXCOUNT 100 int a new intMAXCOUNTthis can be referred to now as a0 a1 etc etc ex Of int loop doube coordinates new doube12 for int i O i lt 6 i coordinates2 i i coordinates2 i 1 Mathsqrti 0 To access the length of an array use the expression arrayNamelength ln arrays length is not a method as in the String class It is accessed like a field without parentheses Ex doube samples new doube10 if i gt 0 ampamp i lt sampesength All indices must fall in the range between 0 and length 1 where length is the number of elements in the array If an index happens to be out of this range your program will throw an Arraylndex0ut0fBoundsException Array element setup ak lt constant variable or expression gt Arrays are always passed to methods as references 124 The ArrayList Class Once an array is created its size can not change A completely new array needs to be made ArrayList allows you to keep a list of values in an array It keeps track of its capacity and size Once the size reaches the ArrayList s capacity you need to add an element The ArrayList automatically increases its capacity by executing code The ArrayList class provides the get and set methods which access and set the i th element These methods check that 0 lt i lt size If your class uses javautiList and javautiArrayList add import javautiList import javautiArrayList An ArrayList holds objects of a specified type When declaring an ArrayList you should specify the type of its elements The type is placed in angle brackets after ArrayList For example private ArrayListltStringgt names or private ArrayListltWakergt family Syntactically the whole combination ArrayList ltsometypegt acts as one long class name which is read an ArrayList of sometypes You need to use the whole thing wheneveryou use the ArrayList I type in declaring variables method parameters and return values and when you create an ArrayList For example Returns an ArrayList with the elements from names rearranged in random order public ArrayListltStringgt scrambedArrayListltStringgt names ArrayListltStringgt result new ArrayListltStringgt An ArrayList like other kinds of java collections can only hold the objects If you try to add a value of a primitive data type to a list the compiler will convert that value into an object of corresponding wrapper class lnterger Double etc For it to work that wrapper type must match the declared type of the list elements For Example ArrayListltDoubegt samples new ArrayListltDoubegt sampesadd50 This wont work sampesadd5can t add an int to an ArrayListltDoubegt An ArrayList can also hold nu s after calls to addnu or add null 125 ArravList s Constructors and Methods ArrayList s noargs constructor creates an empty list size 0 of the default capacity ten Another constructor ArrayListint capacity creates an empty list with a given initial capacity insert example pic on page 331 The elements in an ArrayList are numbered by their indices from 0 to istsize 1 otherwise these methods throw an IndexOutOfBoundsException The addE elmt method appends emt at the end of the list and increments the size of the list by one The add method is overloaded Another method with 2 parameters is addint i E elmt inserts emt into the list so that emt becomes the ith element This method checks 0lt iltistsize and throws an IndexOutOfBoundsException if it isn39t If iistsize then it would worj the same ass the first method The removei method removes the ith element from the list shifts all the subsequent elements to the left by one if there even is one and decrements their indices It also decrements the size of the list by one 126 ArravList s Pitfz You have to be careful with the add and remove methods keep ion mind that they change the indices of the subsequent elements and the size of the list For example ArrayListltStringgt words new ArrayListltStringsgt int n wordssize for int i 0 i lt n i if quotike equaswordsgeti wordsremovei this removes all occurrences of the word like from an ArrayListltStringgt After the first like is found and removed the size of the list words is decremented and becomes smaller than n what it originally was and once i goes past the new list size it will crap out an IndexOutOfBoundsException More concise code to avoid errorsbugs from the one above is int i 0 while i lt wordssize if quotike equaswordsgeti wordsremovei else i I An ArrayList hold references to objects It can hold duplicate values not only equal objects that is obj1equasobj2 but also several references to the same objectthat is obj1 obj2 AN object can changer after it has been added to a list and can belong to several ArrayList s Version 1 public ArrayListltPersongt makeGuestListString names ArrayListltPersongt list new ArrayListltPersongt for int i 0 i lt namesength i istaddnew Personnamesi else l Version 2 public ArrayListltPersongt makeGuestListString names ArrayListltPersongt list new ArrayListltPersongt Person p new Person for int i 0 i lt namesength i psetNamenamesi istaddp return list After the statements String names quotAice quotBob quotCaire ListltPersongt guests makeGuestListnames Systemprintnguests Version 1 when executed shows Aice Bob Claire Version 2 when executed shows Caire Claire Claire 127 Iterations and the For Each Loop A for loop can save 998 lines of code Example int sum 0 for int i 0 i lt 1000 i sum ai AN array or list traversal can be accomplished easily with a simple for loop For example String names new StringnumGuests for int i 0 i lt namesength i String str namesi process str OR AN ARRAYLIST ArrayListltStringgt names new ArrayListltStringgt for int i 0 i lt namessize i String str namesgeti process str
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'