ArrayList - PowerPoint PPT Presentation

1 / 10
About This Presentation
Title:

ArrayList

Description:

... methods for adding and removing. Methods in ... Need to be concerned about type returned by ArrayList method. ... Method. compareTo(Integer intObject) intValue ... – PowerPoint PPT presentation

Number of Views:111
Avg rating:3.0/5.0
Slides: 11
Provided by: Ann9198
Category:
Tags: arraylist

less

Transcript and Presenter's Notes

Title: ArrayList


1
ArrayList
2
java.util.ArrayList
  • Everything stored must be an Object
  • Objects can be different types
  • Size is dynamic, rather than fixed.
  • Provides methods for adding and removing

3
Methods in ArrayList class
4
ArrayList
  • Stored elements may be of different types
  • Example Objects of type Animal, Vegetable, and
    Mineral could all be stored in ArrayList. (Object
    is a superclass of Animal, Vegetable and Mineral.
    All are of type Object)

5
ArrayList
  • Need to be concerned about type returned by
    ArrayList method.
  • Notice Return type for get, set and remove are
    of type Object. If the returned object is to be
    used with a particular class, it needs to be cast
    to that class type.

6
ArrayList
  • Primitives cannot be stored in an ArrayList.
  • Use the wrapper classes Integer and Double
  • public static ArrayList setScores(int numTests)
  • ArrayList scores new ArrayList()
  • for (int k 0 k lt numTests k)
  • int aScore readInt()
  • scores.add(new Integer(aScore)

7
Print the scores
  • public static void printScores(ArrayList scores)
  • for (int k 0 k lt scores.size() k)
  • System.out.println(scores.get(k)

8
Print the highest score
  • public static Integer getMaxScore(ArrayList
    scores)
  • //assume first element is max score
  • Integer max (Integer)scores.get(0)
  • for(k 1 k lt scores.size() k)
  • Integer temp (Integer)scores.get(k)
  • if(temp.compareTo(max) gt 0)
  • max temp
  • return max

9
Understand?
  • ArrayList names new ArrayList()
  • names.add(Alex)
  • names.add(Sam)
  • names.add(0, Tasha)
  • names.add(2, Randy)
  • names.add(2, Sandy)
  • names.add(2, Mandy)
  • names.remove(0)
  • names.remove(2)
  • Tasha, Alex, Mandy
  • Sam, Mandy, Randy
  • Mandy, Sandy, Randy, Sam
  • Alex, Mandy, Randy, Sam
  • NoSuchElement Exception

10
Wrapper classes
  • Primitive data types cannot be stored in an
    ArrayList - elements must be Objects
  • Use Integer and Double used to wrap primitive
    values in an object.
  • Method
  • compareTo(Integer intObject)
  • intValue()
Write a Comment
User Comments (0)
About PowerShow.com