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

Post on 31-Mar-2015

234 views 0 download

Tags:

transcript

JAVA2013.03.06

OUTLINE ArrayList Difference of Array and ArrayList

[Sample code]

TestArrayList.java

ARRAYLIST 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

程式範例 : TESTARRAYLIST.JAVA/* ArrayList */class Car{

int speed(){

return 100;}void run(){

System.out.println("Runing!");}

}

public class TestArrayList{

@SuppressWarnings("unchecked")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());list.add(new Car());System.out.println(((Car)list.get(0)).speed());//System.out.println(((Car)list.get(1)).run());

}}

程式範例 : MYSTACK.JAVA

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

PRACTICE 1. (Sort ArrayList)Write the following

method that sorts an ArrayList of numbers:

Public static void sort(ArrayList<Integer> list)

PRACTICE 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:

Ppt下載: http://oss.csie.fju.edu.tw/~jastine01/

ppt.html