Transcript Java intro

Java intro
Part 3
1
Arrays in Java
• Store fixed number of values of a given type
• Arrays are objects
– have attributes
– must be constructed
• Array declaration:
data type [] name = new data type[int expression];
2
Arrays in Java
• Elements in a new array are automatically
set to 0, false, or null (depending on the
underlying data type)
• Size of an array is stored in its length
attribute; example:
int [] numbers = new int [100];
int size = numbers.length; // stores 100 in size
3
Arrays in Java
• Access to individual members is achieved
via index (subscript), just as it is in C++
• Can construct and initialize an array in a
single statement, such as:
char [] vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’};
4
Anonymous arrays
• Array reference that is not stored in a variable
• Can be used in construction of other objects
• Java’s Polygon class is an example; has
constructor:
Polygon(int[] xvalues, int[] yvalues, int n)
Can construct a triangle using anonymous arrays, as
shown below:
Polygon triangle =
new Polygon(new int[] {0, 10, 5}, new int[] {10, 0, 5}, 3);
5
2-dimensional arrays
• Declaration & construction:
Data type[][] name = new data type [rows][cols];
• As in C++, array is indexed in row-major
order
6
String[] args
• The default parameter to every main()
method is args, an array of String
• This array is used to hold command-line
arguments
– args.length stores the number of arguments
– Each argument is stored as a String from
args[0] to args[args.length-1]
7
ArrayLists
• ArrayList class describes object that can
hold a collection of objects of any type
– objects, not primitive data types
– can use wrapper classes (Integer, Double,
Character, etc.) if ArrayList of one of these
types is desired
• ArrayList class is part of the java.util
package
8
ArrayList methods
• Constructor:
ArrayList myList = new ArrayList();
• doesn’t specify data type or size
• data type is Object, size determined by number of elements
placed in List
• add()
– simplest form just adds element to end of List;
example:
myList.add(“Finish notes before class”);
myList.add(“Get haircut”);
myList.add(“Lather, rinse, repeat”);
9
ArrayList methods
• size(): returns number of elements in List
• get(): returns element at specified position
(between 0 and size() - 1)
String firstItem = (String)myList.get(0);
Since get() returns an Object, need explicit cast
• set(): replaces element at specified location
– first argument: position of element
– second argument: object to place
myList.set(2, “Buy wig”);
10
ArrayList methods
• Insertion of elements in the middle of a list
is accomplished via a call to add() using
two arguments:
– first: position of insertion
– second: object to insert
myList.add(1, “Yet another item”);
11
ArrayList methods
• remove() method removes the element at
the specified position:
myList.remove(0);
• Both add() and remove() move remaining
elements up or down as needed
12
LinkList
• ArrayLists are especially useful for
applications in which random access to
specific elements is desirable
• However, they are inefficient for
applications in which there are frequent
insertions/deletions in the middle of a List
• The LinkList class provides an alternative
for this type of application
13
LinkList
• Part of Java standard library
• Like ArrayList, container for collection of
Objects
• Methods include:
– constructor: LinkedList aList = new LinkedList();
– add(): places element at end of List
– listIterator(): constructs an iterator for traversal of
List (described on next slide)
14
ListIterator()
• Object that can access a position anywhere
within a LinkList
• A LinkList object creates an iterator by
calling its listIterator() method:
ListIterator cursor = aList.listIterator();
• Includes methods for moving through a List
and adding and removing an element from
the List
15
ListIterator methods
• hasNext(): returns true if iterator hasn’t reached
end of List
• next(): returns current element; moves iterator to
next element
while (cursor.hasNext())
{
String s = (String)cursor.next();
System.out.println(s);
}
16
Adding/removing elements
• add() called on iterator inserts element in
position in front of the iterator:
cursor.add(“new element”);
• remove() called on iterator removes the
element in front of the iterator:
cursor.remove();
• If an iterator reaches the end of a list, can
start over by constructing another one
17
Packages
• Groups of Java classes
• Named using dot-separated sets of
identifiers that correspond to the names of
directories in a class’s path
• Base directory of a package is that directory
containing all package directories
• Compilation of a class in a package must
occur in the class’s base directory
18
Placing class in a package
• As the beginning of the source file, use a statement like
the following:
package base.sub1.sub2.subN.current;
– for example, a class in the MYCLASSES subdirectory on
drive a: would contain the statement:
package myclasses;
– if the class name is CLASS1, its full name would be
myclasses.class1
• A source file that doesn’t have a package statement is
considered to be in the default package
19
Internal documentation &
javadoc
• javadoc is a program included with the SDK
(along with javac and java)
• When code has been commented with
specially formatted comments, javadoc
produces HTML pages describing your
classes
20
Format for javadoc comments
• Start with /** and end with */
• First sentence of each comment will be copied by
javadoc to the summary table; should place one
such comment strategically before each class and
each method
• Use @param at the start of a line to describe a
parameter
• Use @return at the start of a line to describe a
return value
21
Guidelines for comments in Java
code
• Supply an informative summary comment in the
first line of documentation for every class and
method
• Supply a description of every parameter and return
value
• Write the comments first, then write the code:
– for class, can use description from CRC card
– for methods, can borrow information from
responsibilities
22
Running javadoc
• At command line, type javadoc *.java
• Produces:
– one HTML file per class
– index.html containing links to other files
• When code is updated, update javadoc
comments at the same time; run javadoc to
update your HTML files
23
Java intro
Part 3
24