CS211 Section Notes prepared by: Alvin Law (ajl56@cornell.edu) ********************** * Strings * * Wrapper classes * * Arrays and Vectors * ********************** String class "this is our text" common methods and functions charcharAt(int index) // character at a certain index boolean equals(Object anObject) // compares equality of strings String concat(String str) // adds str to end of string and returns it int indexOf(int ch) // returns first index of ch in string, -1 if not there String substring(int beginIndex, int endIndex) // returns substring starting at beginIndex and up to but not including endIndex char[] toCharArray() // converts string to character array ********************************************************************** Wrapper Classes - very common for primitives (Integer, Double, Float, etc) - can be used like interface to provide upper level "access" to class (ie lists) common primitive wrapper class functions (borrowed from Integer) boolean equals(Object obj) // compares equality of integers in objects parseInt(String s) // used commonly in command line arguements int intValue() // to get the primitive int compareTo(Object o) // comparison, again because we have objects, not the primitives String toString() // for outputting ease All wrappers of primitives are objects. This makes the use of ==, <, >, and other comparison operators virtually useless. == will compare reference locations, NOT the actual value itself (the ints, for example, in the Integer wrapper class). This is the same reason why Strings, which are objects as well, must use the equals method when testing for equality. ********************************************************************** Arrays vs. Vectors Arrays are static data structures. Once defined, they cannot be resized: int[] myArray = new int[10]; // an int array of length 10 System.out.println(myArray.length); // prints out 10 Arrays' lengths can be accessed without the a function, as shown above. They can also take primitives as field values. Vectors on the other hand are objects. They, unlike arrays, can be resized: import java.util.* // imports many internal utility classes, including Vectors Vector v = new Vector(10); // Vector of size 10 System.out.println(v.size()); // prints out 10 v.setSize(5); System.out.println(v.size()); // prints out 5 Accessing an element from a Vector is a little more cumbersome than accessing one from an array. A list of more common methods: Object elementAt(int index) // returns element at index, which then must be cast (don't forget to do that!!!) boolean isEmpty() // tests if Vector has no elements boolean remove(int index) // remove element at index Object[] toArray() // converts Vector to array