arrays l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Arrays PowerPoint Presentation
Download Presentation
Arrays

Loading in 2 Seconds...

play fullscreen
1 / 41
meena

Arrays - PowerPoint PPT Presentation

116 Views
Download Presentation
Arrays
An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

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

  2. previous | start | next Copying Arrays Copying an array reference yields a second reference to the same arraydouble[] data = new double[10]; double[] prices = data; previous | start | next

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

  4. Partially Filled Arrays

  5. 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++;

  6. 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 arrayif (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;

  7. 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

  8. 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 }

  9. /** add a value to list @param 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++; }

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

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

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

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

  14. /** remove specified element from list @param newval a data value @remove 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--; }

  15. /** checks if list contains specified element @param newval a data value @return 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); }

  16. /** 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 }

  17. 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” );

  18. // 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”); }

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

  20. 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++; }

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

  22. 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] ; }

  23. One problem: remove needs to compare 2 objects for equality

  24. 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--; • }

  25. 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--; }

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

  27. 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)

  28. 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 }

  29. 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); }

  30. 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……….

  31. 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

  32. 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();

  33. The java.util.* package contains a class type which can be used to maintain a list of objects…………. ArrayList http://java.sun.com/j2se/1.4.2/docs/api/index.html

  34. Array Lists • Provided by java.util package • Size is not fixed • Can store objects • Look at spec… http://java.sun.com/j2se/1.4.2/docs/api/index.html

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

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

  37. 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

  38. Removing Elements • remove(i) removes an element at an index

  39. 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……………..

  40. 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();

  41. 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 ……………