Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];

Slides:



Advertisements
Similar presentations
The ArrayList Class and the enum Keyword
Advertisements

Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Chapter 13 Array Lists and Arrays. 2 ArrayList Basics Definition: An array list is a sequence of objects Construct an array List object, i.e. in the Purse.java.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 13 ARRAY LISTS AND ARRAYS. CHAPTER GOALS To become familiar with using array lists to collect objects To learn about common array algorithms To.
Chapter 7 Arrays and Array Lists. Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the.
Chapter 13 ARRAY LISTS AND ARRAYS CHAPTER GOALS –To become familiar with using array lists to collect objects –To learn about common array algorithms –To.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Chapter 7 – Arrays.
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
Chapter 7  Arrays and Array Lists 1 Chapter 7 Arrays and Array Lists.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
Java Syntax Primitive data types Operators Control statements.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
AP Computer Science.  Not necessary but good programming practice in Java  When you override a super class method notation.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Arrays And ArrayLists - S. Kelly-Bootle
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Java Programming Week 6: Array and ArrayList Chapter 7.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors.
Arrays of Objects 1 Fall 2012 CS2302: Programming Principles.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
Information and Computer Sciences University of Hawaii, Manoa
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Fall 2006Slides adapted from Java Concepts companion slides1 Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Arrays. Array: Sequence of values of the same type Construct array: Store in variable of type double[ ] new double[10] double[] data = new double[10];
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
The ArrayList Data Structure Standard Arrays at High Speed!
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Chapter 9 Introduction to Arrays Fundamentals of Java.
An Array-Based Implementation of the ADT List
Principles of Computer Science I
Chapter 8 – Arrays and Array Lists
COP 3503 FALL 2012 Shayan Javed Lecture 8
TCSS 143, Autumn 2004 Lecture Notes
Programming in Java Lecture 11: ArrayList
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Can store many of the same kind of data together
Grouped Data Arrays, and Array Lists.
slides created by Ethan Apter
ArrayLists 22-Feb-19.
Web Design & Development Lecture 6
Presentation transcript:

Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];

Copying Arrays Copying an array reference yields a second reference to the same array double[] data = new double[10]; double[] prices = data; previousprevious | start | nextstartnext previousprevious | start | nextstartnext

Or copy array elements System.arraycopy(from, fromStart, to, toStart, count);

Partially Filled Arrays

Array length = maximum number of elements in array Quite often, array is partially filled Need companion variable to keep track of current size double[] data = new double[DATA_LENGTH]; int dataSize = 0; Update dataSize as array is filled: data[dataSize] = x; dataSize++;

Partially Filled Arrays Remember to stop at dataSize when looking at array elements: for (int i = 0; i < dataSize; i++) sum = sum + data[i]; Be careful not to overfill the array if (dataSize >= data.length) System.out.println("Sorry--array full"); Can grow the array: double newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

IntList.java /** This class provides storage for a quantity of unique, unordered int values and actions which can be performed on those values. */ public class IntList{ private int[] data; //instance variable is array private int dataSize = 0; // keep track of quantity of data

private int[] data; private int dataSize = 0; /** Constructs an empty list. */ public IntList() { final int DATA_LENGTH = 100; data = new int[DATA_LENGTH]; } public IntList( int max) { //overloaded constructor for user data = new int[max]; // flexability }

/** add a value to newval a data value (Precondition: list is not full) (Postcondition: list has one more int value) */ public void add(int newval) { data[dataSize] = newval; dataSize++; }

/** get a value from index a data value (Precondition: list index < size of list) (Postcondition: list does not change) */ public int get(int index) { return data[index] ; }

/** determines if the list is true if list is full, false otherwise (Postcondition: list is unchanged) */ public boolean isFull( ) { return dataSize == data.length; }

/** determines if the list is true if list is emtpy, false otherwise (Postcondition: list is unchanged) */ public boolean isEmpty( ) { return dataSize == 0; }

/** return size of the list (Postcondition: list is unchanged) */ public int size( ) { return dataSize; }

/** remove specified element from newval a data newval from list (Precondition: newval is in list) (Postcondition: list contains one less value */ public void remove(int newval) { int index = 0; // start looking at beginning while ( data[index] != newval) index++; data[index] = data[dataSize-1]; dataSize--; }

/** checks if list contains specified newval a data true if newval is in list (Postcondition: list is not changed) */ public boolean contains(int newval) { int index = 0; // start looking at beginning while (index < dataSize && data[index] != newval) index++; if (dataSize < index) //was it found?? return true; else //or instead of if/else statement, just return false; // return (dataSize < index); }

/** finds largest element in list Return: largest int in the list (Precondition: list is not empty ) (Postcondition: list contains one less value) */ public int largest ( ) { int lrgIndex = 0; // assume largest is the first //look thru the rest for (int index = 1; index < dataSize; index++) if (data[lrgIndex] < data[index]) lrgIndex = index; return data[lrgIndex]; //now return it }

File IntListTest.java import java.util.Random; public class IntListTest { public static void main(String[] args) { Random generator = new Random(); Intlist thelist = new IntList(50); double x = generator.nextDouble(); if (! thelist.isFull() && !thelist.contains( (int) x ) thelist.add( (int) x); else System.out.println(“no element added” );

// output largest if ( ! thelist.isEmpty() ) System.out.println(“largest is list is “ + thelist.largest() ); else System.out.println(“list has no elements !!”); // remove some values from list String strval = JOptionPane.showInputDialog (“enter value to remove ”); while (strval != null) { int value = Integer.parseInt(strval); if (thelist.contains(value) ) thelist.remove(value); else System.out.println( valuel + “ not in list” ); strval = JOptionPane.showInputDialog(“enter value to remove”); }

What if we didn’t want our list to be a fixed size??? It could grow……………

public void add(int newval) { if (dataSize >= data.length) { // make a new array of twice the size int[] newData = new int[2 * data.length]; // copy all elements from data to newData System.arraycopy(data, 0, newData, 0, data.length); // store a reference to the new array in data data = newData; } data[dataSize] = newval; dataSize++; }

What if we didn’t want our list to store a fixed type??? It could be generic with little modification..

Replace all parameter occurrances of the word int with Object public class ObjList{ private Object[] data; // this array stores any kind of object private int dataSize = 0; public ObjList( int max) { data = new Object[max]; } public void add(Object newval) { data[dataSize] = newval; dataSize++; } public Object get(int index) { return data[index] ; }

One problem: remove needs to compare 2 objects for equality

One problem: remove needs to compare 2 objects for equality public void remove(Object newval) { int index = 0; while ( data[index] != newval) //cannot use == or != index++; // to compare objects data[index] = data[dataSize-1]; dataSize--; }

can call compareTo method, and require that objects which are stored in our list implement the Comparable interface… public void remove(Object newval) { int index = 0; while ( data[index].compareTo( newval) != 0) index++; data[index] = data[dataSize-1]; dataSize--; }

Two other problems: contains needs to compare 2 objects for equality can fix this in same way largest needs to compare 2 objects for order can also use compareTo to solve this remove

public Object largest ( ) { int lrgIndex = 0; // assume largest is the first //look thru the rest for (int index = 1; index < dataSize; index++) if (data[lrgIndex] < ( data[index]) ) lrgIndex = index; return data[lrgIndex]; //now return it } FIX IT: if (data[lrgIndex].compareTo( data[index]) < 0)

public class Dog implements Comparable{ private String name; private int age; private int x; y; //x,y drawing position public Dog(int newage) { age = newage ; } public Dog (String nm, int newage, int xpos, int ypos){ name = nm; age = newage; x = xpos; y = ypos; } // Dog objects can be compared public int compareTo (Object obj){ Dog dobj = (Dog) obj; return age - dobj.age; } public void draw(Graphics g){ //etc…………….. g.drawOval(x,y,100,50); g.drawOval(x+12,y+12,5,5); //eyes g.drawOval(x+25,y+12, 5,5); g.fillOval(x+16,y+25, 10,10); //nose g.fillOval(x+62,y+13,50,75); //left ear }

For example, Dog objects can be stored in our list……… public class DogApp{ public static void main(String[] args) { List thelist = new ObjList(50); Dog mydog = new Dog (“SPOT”, 5, 50,50); if (!thelist.full()){ thelist.add(mydog); ….. Code creates and adds more Dog objects… int age = Integer.parseInt (JOptionPane.showInput Dialog(“age of dog to delete”)); Dog temp = new Dog(age); //remove all dogs of given age while( thelist.contains(temp)) thelist.remove(temp); }

Now we can store Strings, Dogs and any other type of object that implements the Comparable interface in our ObjList. What about int values??? Will our application still work?? NO. Because ints are not objects. but we can make them objects……….

Converting ints to objects Java provides wrapper classes Integer, Double, Boolean, Character, etc. An object of class type Integer can ‘wrap’ an int value in an object Integer wrapper = new Integer(55); //wrap the int int unwrapped = wrapper.intValue(); //get int back

Can store wrapper in the list!! mylist.add(wrapper); //can now add it //can get it but remember that method returns Object Integer ival = (Integer) mylist.get(i); unwrapped = ival.intValue();

The java.util.* package contains a class type which can be used to maintain a list of objects…………. ArrayList

Array Lists Provided by java.util package Size is not fixed Can store objects Look at spec…

Adding Elements add adds a new value before the index add(i, c) where i is an int, c is an object

Setting Elements * set overwrites an existing value set(i, M);

Retrieving Array List Elements ArrayList dogSet() = new dogSet(); Dog mydog = new Dog(); dogSet.set(5) = mydog; Use get to retrieve element --must cast to correct type dogSet.get(5).draw(); // no!! Dog temp = (Dog) dogSet.get(5); temp.draw(); Error if index is out of range: int n = dogSet.size(); Dog adog = (Dog)dogSet.get(n); // ERROR // legal index values are 0...n-1

remove(i) removes an element at an index Removing Elements

Would this run using ArrayList?? import java.util.Random; public class IntListTest { public static void main(String[] args) { Random generator = new Random(); ArrayList thelist = new ArrayList(); double x = generator.nextDouble(); thelist.add((int) x); // code which adds more elements while( thelist.contains(x)) thelist.remove( thelist.indexOf(x)); No, because ArrayLists store objects……………..

Use wriapper classes to store primitive values in an ArrayList.. Array lists store objects Use wrapper classes to store numbers Double wrapper = new Double(29.95); double unwrapped = wrapper.doubleValue() ArrayList data = new ArrayList(); data.add(wrapper); unwrapped = ((Double).data.get(i)).doubleValue();

Would this work with ArrayList as the data type?? public class DogApp{ public static void main(String[] args) { ArrayList thelist = new ArrayLIst(); Dog mydog = new Dog (“SPOT”, 5, 50,50); thelist.add(mydog); // Code creates and adds more Dog objects… while( thelist.contains(mydog)) thelist.remove(thelist.indexOf(mydog)); } Yes, as long as the Dog class overrrides equals ……………