Presentation is loading. Please wait.

Presentation is loading. Please wait.

2013.03.06. ArrayList Difference of Array and ArrayList [Sample code] TestArrayList.java.

Similar presentations


Presentation on theme: "2013.03.06. ArrayList Difference of Array and ArrayList [Sample code] TestArrayList.java."— Presentation transcript:

1

2 ArrayList Difference of Array and ArrayList [Sample code] TestArrayList.java

3 You can create an arrayto store objects. But, once the array is created, its size is fixed. Java provides the ArrayList class that can be used to store an unlimited number of objects. Methods in ArrayList

4 /* ArrayList */ class Car { int speed() { return 100; } void run() { System.out.println("Runing!"); } public class TestArrayList public static void main(String[] args) { java.util.ArrayList cityList = new java.util.ArrayList(); cityList.add("Taipei"); cityList.add("Taichung"); cityList.add("Kaushiung"); java.util.ArrayList list = new java.util.ArrayList(); list.add(new Car()); System.out.println(((Car)list.get(0)).speed()); //System.out.println(((Car)list.get(1)).run()); }

5

6 ArrayList objects can be used like arrays, but there are many differences. Once an array is created, its size is fixed. You can access an array element using the square-bracket notation (e.g., a[index]). When an ArrayList is created, its size is 0. You cannot use the get and set methods if the element is not in the list. It is easy to add, insert, and remove elements in a list, but it is rather complex to add, insert, and remove elements in an array.

7 1. (Sort ArrayList)Write the following method that sorts an ArrayList of numbers: Public static void sort(ArrayList list)

8 2.(Largest rows and columns)Write a program that randomly files in 0s and 1s into an n-by- n matrix, prints the matrix, and finds the rows and columns with the most 1s.(Hint:Use two ArrayLists to store the row and column indices with the most 1s.)Here is a sample run of the program:

9 Ppt


Download ppt "2013.03.06. ArrayList Difference of Array and ArrayList [Sample code] TestArrayList.java."

Similar presentations


Ads by Google