1、1,Arrays, Strings and Collections 2,Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia http:/,2,toString() Method,toString() method is a special method that can be defined in any class.This me
2、thod should return a String argument.When an object is used in a String concatenation operation or when specified in print statement, this method gets invoked automatically.,3,toString() Method -Example,class Circle double x, y,r;public Circle (double centreX, double centreY, double radius ) x = cen
3、treX ; y = centreY; r = radius; public String toString()String s = “I am a Circle with centre “ + x + “,” + y + “ and radius “+ r + “”; return s;,4,toString() Method -Example,class CircleTest Circle c = new Circle(10,20, 30);System.out.println( c );/ I am a circle with centre 10.0,20.0 and radius 30
4、.0 ,5,StringBufferClass,Unlike the String class, StringBuffer class is mutable (changeable). Use StringBufferClass class in operations where the string has to be modified.,6,StringBuffer class - Constructors,7,StringBuffer class Some operations,8,Inserting a String in Middle of Existing StringBuffer
5、,StringBuffer str = new StringBuffer(“Object Language”); String aString = new String(str.toString(); Int pos = aString.indexOf(“ Language”); str.insert(pos, “ Oriented “); what will out put of at this point: System.out.println(“Modified String:”+str); What will be string after executing (modifying c
6、haracter): str.setChar(6,-);,9,StringTokenizer,Breaks string into parts, using delimiters. The sequence of broken parts are the tokens of the string. More than one delimiter can be specified. The tokens can be extracted with or without the delimiters.,10,StringTokenizer - Functionality,Consider the
7、following String CREATE_USER:1234567;John;SmithSeparate the tokens CREATE_USER 1234567 John Smith,11,StringTokenizer - Constructors,12,StringTokenizer - Operations,13,StringTokenizer - example,Output of the program CREATE_USER 123456 John Smith,import java.util.StringTokenizer; class TokenizerExampl
8、e public static void main(string args)String str = “CREATE_USER:123456;John;Smith”;StringTokenizer tokens = new StringTokenizer(str, “:;”);while ( tokens.hasMoreTokens() )System.out.println(tokens.nextToken(); ,14,Collections,Arrays are used to hold groups of specific type of itemsCollections (conta
9、iner) designed to hold generic (any) type of objectsCollections let you store, organize and access objects in an efficient manner.,15,Legacy Collection Types,Vector Stack Dictionary HashTable Properties Enumeration,16,Vector,The Vector class implements a growable array of objects. Like an array, it
10、contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. In Java this is supported by Vector class contained in java.util package. The Vector class can be us
11、ed to create generic dynamic arrays that hold objects of any type or any number. The objects do not have to be homogeneous. Like arrays, Vectors are created as follows: Vector list = new Vector(); / declaring without size Vector list = new Vector(3); / declaring with size,17,Vector properties,Vector
12、s posses a number of advantages over arrays: It is convenient to use vectors to store objects. A vector can be used to store list of objects that may vary in size. We can add and delete objects from the list as an when required. But vectors cannot be used to store basic data types (int, float, etc.)
13、; we can only store objects. To store basic data type items, we need convert them to objects using “wrapper classes” (discussed later).,18,Important Methods in Vector class,addElement(Object item) insertElementAt(Object item, int index) elementAt(int index) get element at index removeElementAt(int i
14、ndex) size() clone() - Returns a clone of this vector. clear() - Removes all of the elements from this Vector. get(int index) - Returns the element at the specified position in this Vector. copyInto(array) copy all items from vector to array.,19,Vector Example 1,import java.util.*;public class Vecto
15、rOnepublic static void main(String args) Vector circleVector = new Vector();System.out.println(“Vector Length + “, circleVector.size(); / 0for ( int i=0; i 5; i+) circleVector.addElement( new Circle(i) ); / radius of the Circles 0,1,2,3,4 System.out.println(“Vector Length = “ + circleVector.size();/
16、 5 ,20,Vector Example 2,import java.util.*; public class VectorTwopublic static void main(String args) code from VectorOne goes herecircleVector.insertElementAt( new Circle(20), 3);System.out.println(“Vector Length =“ + circleVector.size(); / 6for ( int i = 0; i 6; i+)System.out.println(“Radius of e
17、lement “ + i + “ = “+ ( (Circle) circleVector.elementAt(i).getRadius();/ radius of the Circles are 0,1,2,20,3,4 ,21,Hash Table (Hashtable clalss),Allows associating values with keys. Allows efficient look ups for the value associated with the key This class implements a hashtable, which maps keys to
18、 values. Any non-null object can be used as a key or as a value. Useful Operations: put(Object key, Object value); remove(Object key); get(Object key);,22,HashTable put()/get() operations,The following example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable number
19、s = new Hashtable(); numbers.put(“one“, new Integer(1); numbers.put(“two“, new Integer(2); numbers.put(“three“, new Integer(3); To retrieve a number, use the following code: Integer n = (Integer)numbers.get(“two“); if (n != null) System.out.println(“two = “ + n); ,23,HashTable -Example,import java.u
20、til.*; public class HashtableDemo public static void main(String args) Hashtable tbl = new Hashtable();Student s, sRet;s = new Student(“121212“, “John“);tbl.put (s.getId(), s);s = new Student(“100000“, “James“);tbl.put (s.getId(), s);sRet= (Student) tbl.get(“121212“);System.out.println(“Student name
21、 is = “ + sRet.getName();/ Student name is = John ,24,Enumeration,Used to enumerate or iterate through a set of values in a collection. Useful for iterating Hashtables no index. Useful Operations: hasMoreElements(); nextElement();,25,Enumeration - Example,import java.util.*; public class Enumeration
22、Demopublic static void main(String args) Hashtable tbl = new Hashtable();Student s, sRet;s = new Student(“121212“, “John“);tbl.put(s.getId(), s);s = new Student(“100000“, “James“);tbl.put(s.getId(), s);Enumeration e = tbl.elements();while ( e.hasMoreElements() sRet = (Student) e.nextElement();System
23、.out.println(“Student name is = “ + sRet.getName();/ Student name is = James/ Student name is = John ,26,Wrapper Classes,As pointed out earlier, collections cannot handle basic data types such as int, float. They can converted into object types by using the wrapper classes supported by java.lang pac
24、kage.,27,Methods in Wrapper Classes,Constructors: Integer intVal = new Integer(i); Float floatVal = new Float(f); Converting objects to basic values int i = intVal.intValue(); float f = floatValue.floatValue(); Converting Numbers to Strings str = Integer.toString(i) str = Float.toStrin(f);,28,Method
25、s in Wrapper Classes,String Objects to Numeric Objectrs Integer intVal = Integer.ValueOf(str); Float floatVal = Float.ValueOf(str); Numeric Strings to Basic Types int i = Integer.parseInt(str); long l = Long.parseFloat(str) These methods throw exception (NumberFormatException) if the value of the st
26、r does represent an integer. Exception are a OO way of reporting errors. More on it later.,29,Summary,A special method, toString(), can be defined in any Java class, which gets invoked when one tries to concatenation operation with Strings. Collections are like arrays, but can hold any objects, dynamically expandable, and supports their easy manipulation. Java has strong support for Collections, which are very useful when developing large-scale software development. Wrapper classes helps in manipulating basic data types as Objects.,