Arrays and ArrayLists

Arrays and ArrayLists

Arrays and ArrayLists Array Before we have only looked at single variables. An array can hold a number of variables. int[] anIntArray; // declares an array of integers anIntArray = new int[10]; // allocates memory for 10 integers Can hold primitive data types and objects.

Length of an array

To the the size of an array use .length Is this a method? Useful when iterating through an array for(int i = 0; i < anIntArray.length; i++) { System.out.println("Element at index "+i+": " + anIntArray[i]); } Common error Out of bounds exception. Arrays benefits Arrays are good when you know how many elements you will have to deal with. However, if the number of elements is not known, or may change we have to manage an array. Deleting elements in an array and shuffling

elements can be tricky and error prone. Sorted/Unsorted Arrays. ArrayList An ArrayList can be thought of as a variable length array. Elements/items can be added and deleted, and inserted at a given position. import java.util.ArrayList;

Declare an arrayList ArrayList stringList = new ArrayList(); //note that we must state the data type of the variables we are going to store. In this case the data type is String Adding an element

Here we add two strings stringList.add("John"); stringList.add("David"); Note that we cannot add something of a

different data type we will get a compile time error add(int index, E element) Inserts the specified element at the specified position in this list. It also shifts all elements up by one position And of course the size of the ArrayList has increased by one.

Contains We can ask if the arrayList stringList contains a given String The method will return true or false E.g. stringList.contains("John") Is it Empty We could check if an arrayList is empty like

this if(stringList.size() == 0){ System.out.println("ArrayList is empty"); } isEmpty() method returns true if this ArrayList contains no elements. Removing an Item at an Index stringList.remove(0);

This will remove the item at position/index 0 It will also shuffle all the elements down by one position. So the arrayList is now shorter by one elements Check this with the size() method. Replacing an element use set (int index, E element) method of java ArrayList

to replace any element from a particular index. Below code will replace first element of stringList with AAA". stringList.set(0,AAA"); Set index 0 to AAA Clearing an ArrayList To reset an ArrayList just call the method clear() This will remove all the data, and set the size

to zero Confirm by calling method size(). indexOf and lastIndexOf indexOf Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. lastIndexOf

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. addAll So far we have only added/deleted single elements addAll(Collection c) Appends all of the elements in the specified collection to the end of this list, in the order that

they are returned by the specified collection's Iterator. addAll(int index, Collection c) Inserts all of the elements in the specified collection into this list, starting at the specified position. removeRange removeRange(int fromIndex, int toIndex) Removes from this list all of the elements whose

index is between fromIndex, inclusive, and toIndex, exclusive. BE CAREFUL WITH off by one errors!!! We (computer scientists) start counting at zero (most computer languages), which means the last elements of ArrayList size n is n-1, and the first (1st) has index zero.

Recently Viewed Presentations

  • Survival ASL - Anoka-Hennepin School District 11

    Survival ASL - Anoka-Hennepin School District 11

    Survival ASL. Everything you need to know to . survive ASL class. BATHROOM. WATER+FOUNTAIN. NURSE. ... GOOD+MORNING. BATHROOM GO-TO I, PLEASE? SICK ME. NURSE GO-TO I, PLEASE? ... Non-Manual Markers are facial expressions used to denote certain grammatical aspects of...
  • Defibrillation - Fleming College

    Defibrillation - Fleming College

    Defibrillation Must be 25 lbs pressure with paddles or good contact with skin on pads to ensure good contact and success of defibrillation Can also defib anterior/posterior but more difficult and cumbersome in the VSA patient (imagine large VSA patient)...
  • Geeks bearing graphs? Economists and economics at the

    Geeks bearing graphs? Economists and economics at the

    "The Conservative Party is committed to making cash cuts of £35 billion from Labour's public spending plans - cuts so large they could only be found from cutting deep into front-line public services, including schools, hospitals and the police." (Alistair...
  • Linda Li, PT, PhD @Arthritis_UBC Using KT model

    Linda Li, PT, PhD @Arthritis_UBC Using KT model

    Nick Bansback Lynne Feehan. Elaine Yacyshyn Allyson Jones. Jacek Kopec Paul Adam. Alison Hoens. Catherine Backman. Patient . p. artners: Cheryl Koehn, Alison Hoens, Kelly English, Karen Tsui, Otto Kamensek, Sheila Kerr, Lianne Gulka, Annette McKinnon, Ruta Cumming, Pam Monte,...
  • The Different Other: Listening to Scripture about Things

    The Different Other: Listening to Scripture about Things

    in the Church as a Celibate Gay Christian (Brazos, 2015). Majority-Other obligations within Spiritual Family? 1. Awareness is power! That is, awareness of the "norming" power of majority group views, styles, preferences, etc. 2. Intentionality to the "voice" of minority...
  • Content of these slides: Slides 2-31...........Induction machines Slides

    Content of these slides: Slides 2-31...........Induction machines Slides

    * Good resources for power electronics: Section 4 of Module PE-IM posted on course webpage Chapter 12 of Kirtley Good resources for induction machines: Sections 1-3 of Module PE-IM posted on course website Chapter 13 of Kirtley Take EE 459/559...
  • Steven F. Ashby Center for Applied Scientific Computing Month ...

    Steven F. Ashby Center for Applied Scientific Computing Month ...

    Anomaly/Outlier Detection What are anomalies/outliers? The set of data points that are considerably different than the remainder of the data Variants of Anomaly/Outlier Detection Problems Given a database D, find all the data points x D with anomaly scores greater...
  • Class 7 - My Brother Jesus

    Class 7 - My Brother Jesus

    Overview of today's class on the Catholic Church: The foundation of the Catholic Church by Jesus Christ. The . twelve Apostles, how Christ chose them, how He chose St. Peter to be the head of the early Church, ... "The...