• Construct array:
new double[10]
• Store in variable of type double[]:
double[] data = new double[10];
• When array is created, all values are initialized depending on
array type:
• Numbers: 0
• Boolean: false
• Object References: null
Syntax Array
double [] values = new double[10]
double[] moreValues = { 32,54,67,5,29,35};
Use brackest to acces an element
values[i] = 29.95;
Array Lists
• ArrayList class manages a sequence of objects
• Can grow and shrink as needed
• ArrayList class supplies methods for many common tasks,
such as inserting and removing elements
• ArrayList is a generic class:
ArrayList<T>
collects objects of type parameter T:
ArrayList<String> names = new ArrayList<String>();
names.add("Emily");
names.add("Bob");
names.add("Cindy");
• size method yields number of elements
Adding Elements
To add an object to the end of the array list, use the add
method:
names.add("Emily");
names.add("Bob");
names.add("Cindy");
Syntax ArrayList
ArrayList<String> friends = new ArrayList<String>();
friends.add("Eko");
String name = friends.get(i);
friends.set(i,"Harry");
/arraylist/ArrayListTester.java
1.import java.util.ArrayList;
2
3 /**
4 This program tests the ArrayList class.
5 */
6 public class ArrayListTester
7 {
8 public static void main(String[] args)
9 {
10 ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
11 accounts.add(new BankAccount(1001));
12 accounts.add(new BankAccount(1015));
13 accounts.add(new BankAccount(1729));
14 accounts.add(1, new BankAccount(1008));
15 accounts.remove(0);
16
17 System.out.println("Size: " + accounts.size());
18 System.out.println("Expected: 3");
19 BankAccount first = accounts.get(0);
20 System.out.println("First account number: "
21 + first.getAccountNumber());
22 System.out.println("Expected: 1008");
23 BankAccount last = accounts.get(accounts.size() - 1);
24 System.out.println("Last account number: "
25 + last.getAccountNumber());
26 System.out.println("Expected: 1729");
Kamis, 02 Mei 2013
Array dan ArrayList
21.44
Unknown
2 comments
2 komentar:
thx gan..sangat bermanfaat..
di tunggu postingan selanjutnya..
Posting Komentar