Lecture 9. Disjecta membra

concepcionsockΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 4 χρόνια και 10 μήνες)

252 εμφανίσεις

Lecture 9

Wrappers and Storage

Review


We can treat subclass objects as superclass
objects, provided we don’t use any subclass
methods.


E.g…


menuItem.addActionListener(ourListener);


Even though it takes in an
ActionListener
.



Most objects in Java invisibly extend
java.lang.Object.

This Lecture


We’ll look at storing and altering data.



Simple types and their wrapper classes


Objects that hold geographical space and time.


Array alternatives


objects for holding other
objects


The Art of Programming Part Nine: IDEs


Next lecture

Wrappers for simple types


The simple types are ok, but they don’t have any
great abilities.



Those crazy scientists at Sun just couldn’t resist
tinkering, so they made a set of objects to give
simple types methods.



These objects act as containers for simple types,
and give them extra functionality.



We call such containers “wrappers”.

Wrapper types


java.lang.Boolean


java.lang.Byte


java.lang.Character


java.lang.Double


java.lang.Float


java.lang.Integer


java.lang.Long


java.lang.Short


java.lang.String



We’ve already used
String

a lot


it wraps
character arrays.

java.lang.Number


Most wrappers implement
java.lang.Number


Therefore they have methods to return


byte


double


float


int


long


short


String


String numStr = “3”;


Integer inte = new Integer(numStr);


int numInt = inte.intValue();

Useful methods : To infinity and beyond…


Double.isInfinite(double value)

DoubleObject.isInfinite()

Double.isNaN(double value)

DoubleObject.isNaN()


Float has the same methods.


double d = 0;

if (Double.isInfinite(1/d)) {


// This is done.

}


Double dD = (0/1);

if (dD.isNaN()) {


// This is done.

}

Useful methods: Decode


decode


in an number of the wrappers.


Used to convert hexadecimal and octal to decimal
numbers.


Hex numbers should start # or 0x


Oct numbers should start 0



int dec = Integer.decode(0xFF);


dec == 255


Integer.toHexString(int
value
)


Useful methods: Character conversion


All characters have a number which represents them. Some
objects only take in characters as numbers.


Character.getNumericValue(char
ch
)



You can then cast the int back into a char.


char c = (char) intValue;



All chars are part of a set of 16 bit international characters
called Unicode.



These extend the American Standard Code for Information
Interchange (ASCII) , which are represented by the ints 0 to
127, and its superset, the 8 bit ISO
-
Latin 1 character set (0 to
255).


To use stuff like newline characters, you need to use escape
strings.

Useful methods: String searches

startsWith(String prefix)
,
endsWith(String suffix)

Returns a boolean.


indexOf(int ch)
,

indexOf(int ch, int fromIndex)


Returns an int representing the first position of the first
instance of a given Unicode character integer to find.


indexOf(String str)
,





indexOf(String str, int fromIndex)


Returns an int representing the position of the first instance
of a given String to find.


lastIndexOf


Same as indexOf, but last rather than first.

Useful methods: String manipulation

replace(char oldChar, char newChar)



Replaces one character with another.


substring(int beginIndex, int endIndex)


Pulls out part of the String and returns it.


toLowerCase()
,
toUpperCase()



Changes the case of the String.


trim()


Cuts white space off the front and back of a String.

java.util.StringTokenizer

StringTokenizer st = new







StringTokenizer(“
call me bob
");

while (st.hasMoreTokens()) {


println(st.nextToken());

}


prints the following output:

call

me

bob



Default separators:
space
,

tab
,

newline
,

carriage
-
return character, and form
-
feed
.




Simple types and their wrapper classes


Objects that hold geographical space and
time.


Array alternatives


objects for holding other objects


The Art of Programming Part Nine: IDEs


Next lecture

Objects that hold geographical
space and time.


java.util.Date



java.util.Calendar /
java.util.GregorianCalendar



java.util.TimeZone



java.util.Locale

Date


new Date(long
milliseconds
)


System.currentTimeMillis()


Where
milliseconds

is since January 1, 1970,
00:00:00 GMT.



Methods to find if a date is before or after a Date, or
set the date in it.

Calendar


Calendar classes wrap around Date objects and
interpret them in times of a particular calendar
type.



Returns calendar dependant months and years.



For example, GregorianCalendar implements the
system the UK officially uses.



GregorianCalendar has methods appropriate to
this system


e.g.
isLeapYear(int
year
)


TimeZone and Locale


TimeZone allows you to stipulate the time zone
relative to Greenwich Mean Time (GMT) /
Coordinated Universal Time (UTC).



Locale objects allow you to encapsulate the
language and country the software is in.



Both are usually set at install by the user.

Summary


There are wrappers for all the simple types.
These give them extra functionality.


This functionality includes…


Converting to other types that can’t be cast.


Testing numbers for infinity and division by zero.


Converting between bases.


Searching and manipulating Strings.


There are also wrappers for geographical time
and space. These allow us to internationalise our
software.



Simple types and their wrapper classes


Objects that hold geographical space and time.


Array alternatives


objects for holding
other objects


The Art of Programming Part Nine: IDEs


Next lecture

Array alternatives: the util storage
classes


Classes in java.util that allow you to store objects
like arrays do


only easier.


However, they are less efficient than arrays and
take up more memory.



java.util.Vector


java.util.Stack


java.util.Hashtable


java.util.Properties


java.util.Bitset


java.util.Enumeration

Vector


Like an array, however, of variable size.


Vector()

Vector(int
size
)

Vector(int
size
, int
increment
)



When full, the Vector doubles in size, or increases
by the
increment

given.


Vector methods

addElement(Object
ob
)

insertElementAt(Object
ob
, int
index
)


Add elements in at the top or
index

position.


elementAt(int
index
)


Gets an element at the
index

position.


contains(Object
ob
)


Checks the object is in the Vector.


The need to cast


All Vector items are stored as java.lang.Object.


Vector v = new Vector();

Point here = new Point();

v.addElementAt(here,0);



Point hereRef = (Point) v.elementAt(0);

Stack


Stacks are “piles” of objects. You can only add to
the top of them, and take the top one off.


push(Object
ob
)


Puts an object at the top of the stack.


pop()


Returns the object at the top of the stack and
removes it.


peek()


Returns the object at the top of the stack, but
doesn’t remove it.

Hashtable


Stores pairs of objects: one a key, and the other
data.


For example, you might have Strings representing
the name of someone, and data representing their
addresses…



Key



Data


“Garry Hobbs”


“3 Albert Sq., Walford, E20, London.”


“Pat Evans”



“31 Albert Sq., Walford, E20, London.”

Hashtable


Hashtables store the key as a value known as the
hashcode. This is generated from the key object
by its
hashCode()

method.



All objects stored in a Hashtable must have a
hashCode()

method. Most wrapper classes do.


Methods…


put(Object
key
, Object
value
)


get(Object
key
)


remove(Object
key
)

Properties


Subclass of Hashtable, only taking in String keys
and String data.


You can pass another Properties object into the
Properties constructor allowing nesting.


If the key isn’t found the nested Properties are
examined.


The most powerful methods are…


load(InputStream
in
)


save(OutputStream
out
)


…which make it easy to save and retrieve
Properties from files.

Others: BitSet and Enumerations


BitSet
-

variable array of bits.


Can be used to manipulate lengths of bits using bit
operators: AND; OR; XOR.



Enumeration



interface dictating a class that lets you step
through the objects inside it. They have two methods…




hasMoreElements()



nextElement()



Most of these classes / interfaces are Iterators
-

they let you
step through their stored objects without knowing how.

Enumerations from Vectors

Useful bit of code when dealing with Vectors of an
unknown size.


Enumeration en = vector.elements();


while (en.hasMoreElements()) {


someObject = (CastClass) en.nextElement());

}



Simple types and their wrapper classes


Objects that hold geographical space and time.


Array alternatives


objects for holding other objects


The Art of Programming Part Nine: IDEs



Next lecture

The Art of Programming: Tooling Up


When you do real programming, it’s unlikely you’ll
do it with Wordpad and the command line compiler.



You’ll probably use an Integrated Development
Environment (IDE).



These make your life easier.



They take a little time to learn to use, but are worth
the investment in time and money.

What do IDEs do?


Usually have Syntax colouring (e.g. will colour keywords,
strings, method names etc.)



Usually have one
-
push compiling and running.



Usually have run
-
time debugging


stops when your code
breaks, shows you where, and tells you the problem.



Usually have a facility for stepping through code one line at
a time, and watching how variables change.



Often have “auto
-
complete” drop down lists


you type an
Object’s name, and they give drop
-
down lists of the
potential methods.

Other Functions Some Have


Rapid Application Development (RAD)


The software lets you draw GUIs and writes the code for
you. It may or may not then let you alter that code.



Computer Aided Software Engineering (CASE)
Tools


CASE tools help structure the development process. They
may contain facilities for generating UML, converting UML
into code, and for seeing which classes are dependent on
each other.



Optimisation tools/Profilers/Refactoring tools


Show unused code and speed bottlenecks.


Allow quick altering of multiple files.

Popular Commercial Java IDEs

Sun Java Studio (Uses Sun’s free IDE: “Netbeans”)


Pros: Drop
-
down method lists, RAD, free extension
modules, syntax highlighting, profiling.


Cons: Needs a good computer to run it.


JBuilder (Borland: based on Eclipse)


Pros: Drop
-
down method lists, RAD + easy templates for
non
-
GUI programs.


Cons: Tends to include a lot of its own non
-
standard
classes, making it hard to work with others.


Eclipse (IBM: Free)


Pros: Simple, popular.

Sun Java Studio / Netbeans


Important it is set up to write to
m:/netbeans/

Other Tools


Other IDEs


Editors (less functions, often just syntax colouring)


Notepad++; jEdit; Emacs (for the true geeks).


UML Tools


Dia (free), Rational Rose.


Stand alone Profilers


jProbe (expensive but good).


Decompliers (take Classes and turn them into code


you
take your chances downloading these).


Obfuscators (mash up Classes so they work but can’t easily
be decomplied).


See the list at http://www.alife.co.uk/links/jdev/

Summary


There are wrappers for all the simple types. These
give them extra functionality.


This functionality includes…


Converting to other types that can’t be cast.


Testing numbers for infinity and division by zero.


Converting between bases.


Searching and manipulating Strings.


There are also wrappers for geographical time and
space. These allow us to internationalise our
software.

Summary


There are also more complex wrappers that act as arrays


the util storage classes. However, they’re not very efficient
and take up more memory than arrays.


Vectors act like self
-
expanding arrays.


Stacks are like piles of objects


you can only add and take
from the top.


Hashtables and Properties allow you to store a key and a
dataset. The key lets you easily locate the associated data.
Properties can be used with streams.


BitSets contain bit arrays.
Enumeration

is an interface for
objects that let you step through their elements.


All these are types of Iterator
.


Next Lecture


Interacting with the processor and
memory.


Interacting with programs outside the JVM.


Customizing ArcGIS.


Next Practical:


Groups


Projects