Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Zaawansowane programowanie obiektowe Lecture 3 Szymon Grabowski [email protected] http://szgrabowski.kis.p.lodz.pl/zpo/ Thx to Wojciech Bieniecki for sharing stuff and friendly advices Łódź, 2009 1 java.math.BigInteger A class to represent arbitrarily large integers (signed). Supports add, substr, mul, div etc. – and less standard operations: GCD calculation, primality testing, prime generation, bit manipulation and more. BigInteger b1 = new BigInteger(new String("12111301"), 4); // in base 4; it's 25969 BigInteger b2 = new BigInteger(new String("59")); // default base 10 BigInteger b3 = b1.divide(b2); // 25969 / 59 = 440 (integer division) BigInteger b4 = BigInteger.valueOf(350L); int i = b4.intValue(); // there are: doubleValue(), longValue()... 2 System.out.println(b4 + " = " + i); BigInteger example [ Core Java, vol. 1, ch. 3, http://authors.phptr.com/corejava/downloads/coreJava6v1_0130471771.zip ] 3 Java Collection Framework, basics A collection is an object that represents a group of objects (such as e.g. Vector). A collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. Why using JCF? • less programming effort (useful data structures and algorithms provided), • good performance (often not that easy to implement so efficient and robust structures / algs on one’s own), • easier to understand code (esp. someone else’s). 4 The components • interfaces (such as sets, lists and maps) • implementations • algorithms (static methods that perform useful functions on collections, such as sorting a list) • iterators If you know C++ STL, you’ll be Java collections expert in zero time... 5 Basic collections • lists: sequential or random access; duplicates allowed • sets: no indexed access, duplicates forbidden • maps aka dictionaries, associative arrays Interfaces and implementations in Java 2. Prior to Java 2 also Vector and Hashtable were allowed (they still are). 6 Let’s start from an array... Pros: • knows the type it holds, i.e. compile-type checking • knows its size • can hold primitive types directly (=no wrapping). Cons: • fixed size (=static) • can hold only one type of objects. Helper class: java.utils.Arrays with basic functionalities (public static methods): • equals() • fill() // instantiation • asList() // conversion • binarySearch(), sort() 7 Sorting an array [ http://javaalmanac.com/egs/java.util/coll_SortArray.html?l=rel ] 8 Displaying an array Printing an array: System.out.println(Arrays.asList(strArray)); // will print e.g. [C, a, z] But this won’t work (as we could expect) for intArray (the topmost array at the previous slide). Solution: either print it naïvely, e.g.: for(int i=0; i<intArray.length; i++) System.out.print(intArray[i]+" "); ...or use an object type Integer instead of int: Integer[] intArray = new Integer[] {4, 1, 3, -23}; 9 java.util.Arrays methods (1/13) equals – overloaded for each primitive type plus one more for Object arrays: for the case of Object arrays, two objects o1, o2 are equal if either both are null, or o1.equals(o2). Integer[] intArray1 = new Integer[] {4, 1, 3, -23, 0}; Integer[] intArray2 = new Integer[] {4, 1, 3, -23}; String modifier = ""; if (Arrays.equals(intArray1, intArray2)==false) modifier = "not "; System.out.println("The compared arrays are " + modifier + "identical."); 10 java.util.Arrays methods (2/13) Another Arrays.equals() example – BEWARE! 11 java.util.Arrays methods (3/13) toString (appeared in Java 5.0) – supports printing arrays. String[] arr = new String[] { "horse", "cat", "boa constrictor" }; System.out.println(Arrays.toString(arr)); // output: [horse, cat, boa constrictor] For multi-dim arrays, use deepToString(). String[][] arr = new String[][] { { "deepToString", "1" }, { "deepToString", "2" }, { "deepToString", "3" } }; System.out.println(Arrays.deepToString(arr)); // output: [[deepToString, 1], [deepToString, 2], [deepToString, 3]] Last example: what if we forget and use toString()? Output: [[Ljava.lang.String;@1f6a7b9, [Ljava.lang.String;@7d772e, [Ljava.lang.String;@11 b86e7] 12 java.util.Arrays methods (4/13) fill – fills elements in array of the same type with the value argument. Overloaded for each primitive type and Object. void fill (type[] array, type value) void fill (type[] array, int fromIndex, int toIndex, type value) short[] shArr = new short[7]; Arrays.fill(shArr, 2, 6, (short)81); for(int i=0; i<shArr.length; i++) System.out.print(shArr[i]+" "); // output: 0 0 81 81 81 81 0 Wanna print with asList()? Short[] shArr = new Short[7]; Arrays.fill(shArr, 2, 6, new Short((short)81)); System.out.println(Arrays.asList(shArr)); // output: [null, null, 81, 81, 81, 81, null] 13 java.util.Arrays methods (5/13) sort – overloaded for each primitive type (except boolean), plus one more for Object. The array will be sorted in ascending order. void sort(type[] a) // uses quick sort for primitive types, // O(n log n) avg time // acc. to numerical order void sort(Object[] a) // uses merge sort for object types // stable and O(n log n) worst case time // acc. to natural ordering of its elements // all the array elements must implement // the Comparable interface 14 java.util.Arrays methods (6/13), sort example [ http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html ] Now, invoke Arrays.sort(persons); ? No; it would throw ClassCastException. 15 java.util.Arrays methods (7/13), sort example, cont’d [ http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html ] Solution: of course we have to implement Comparable interface. It has one method, compareTo, which determines how to compare two instances of the class. public int compareTo(Object o) /* returns 0 if equal, a negative integer if the curr object is smaller than o, and a positive integer otherwise */ 16 java.util.Arrays methods (8/13), sort example, cont’d [ http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html ] instanceof Now, in some other class (e.g. called Testing) we create several Person objects, they are stored in e.g. array persons, and sort them with Arrays.sort(persons). 17 java.util.Arrays methods (9/13), using java.util.Comparator [ http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html ] Ok, we can sort objects using Comparable, why bothering with another interface (Comparator)? That’s because objects sometimes need to be compared in different ways (e.g. people – by their last names in lex. order, or by birth date, or first ordered by their position in the office etc.). Idea: pass an external object to method sort(...). An object of a class implementing Comparator interface. java.util.Comparator interface has one method: public int compare(Object o1, Object o2) // o1 less than o2 – return a negative int etc. 18 java.util.Arrays methods (10/13), using java.util.Comparator, example [ http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html ] 19 java.util.Arrays methods (11/13), using java.util.Comparator, example, cont’d [ http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html ] 20 java.util.Arrays methods (12/13), using java.util.Comparator, example, cont’d [ http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html ] Testing the Comparator objects: create some extra class (e.g. Testing), create an array persons in it, fill it with data, then call Arrays.sort(persons, new FirstNameComparator()); or Arrays.sort(persons, new LastNameComparator()); Problem is, if we need n comparison criteria, we also need to create n extra classes. Lots of clutter. This can be mitigated by making the comparators anonymous classes (next lecture...). 21 java.util.Arrays methods (13/13) binarySearch – overloaded for each primitive type (except boolean), plus one more for Object. The array must be sorted in ascending order. int binarySearch (type[] array, type key) int binarySearch (Object[] array, Object key, Comparator comp) It returns the index to the position where the key is found (if duplicates exist, we cannot be sure about the exact position!), or if it is not found, to the insertion point. (If key greater than all the items, the method returns array.length.) Binary search in a sorted array of size n: O(log n) worst-case time. Don’t you ever binary search in an unsorted array! (Result would be unpredictable.) 22 Binary search example [ http://www.cs.princeton.edu/introcs/42sort/images/20questions.png ] 23 ArrayList – dynamic array In many scenarios we cannot estimate the size of the needed structures even very roughly (for example, when reading data from a file, which can be either small, medium-size or huge). ArrayList class (from java.util) implements a dynamic array; fundamental methods: • add(element) • get(index); • size(). 24 ArrayList, example ([Barteczko’04]) We use BufferedReader class. 25 ArrayList, example, cont’d ([Barteczko’04]) Alternative for traversing the list: ... // display all Iterator it = list.iterator(); while (it.hasNext()) System.out.println(it.next()); Output, for example: MS Intel Sun Intel KIS Computing Duplicates! To avoid them, use a set structure, not a list. 26 Sorting an ArrayList Use the method sort from Collections: ... String s; ArrayList list = new ArrayList(); while (...) list.add(s); // ArrayList of Strings Collections.sort(list); Iterator it = list.iterator(); for(int i=0; it.hasNext(); i++) ... = (String) it.next(); 27 List interface [ http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html ] List – an ordered collection (sequence). Precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list, starting from 0), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. (Someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but it’s not typical.) 28 List interface, cont’d Selected methods (“opt” – optional): opt opt opt opt opt opt void add(int index, Object element) boolean add(Object o) // false if the Object o was not added boolean addAll(Collection c) // true if the list changed as a result void clear() boolean contains(Object o) Object get(int index) int indexOf(Object o) // -1 if the list doesn’t contain element o boolean isEmpty() int lastIndexOf(Object o) Object remove(int index) // Returns the element removed Object set(int index, Object element) // replaces an item at index int size() 29 List implementations, short comparison ArrayList – internally an array, so it has O(1) access to an indexed item, but slow (O(n)) update (insert / delete) from the middle of the structure. LinkedList – fast (constant-time) update in a pointed position, slow access (O(n) – needs traversal over the list). From [Cormen, McGraw-Hill, 2000, p. 205] Doubly-linked list. (b) After inserting key 25, (c) after deleting key 4. 30 The Set interface Sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. SortedSet interface extends Set interface. An implementation of SortedSet is TreeSet. You can create a TreeSet object like that: SortedSet ts = new TreeSet(); 31 Using SortedSet [ http://javaalmanac.com/egs/java.util/coll_SortSet.html?l=rel ] Note the iterators. YOU CANNOT USE a for(int i=0; i<set.size(); i++) { ... } loop here! 32 Sets import java.util.*; class SetDemo { static public void main(String[] args) { System.out.println("\n---sets---"); HashSet b1 = new HashSet(); b1.add("dog"); b1.add("cat"); b1.add("dog"); System.out.println(b1); // prints "[dog, cat]" Set b2 = new HashSet(); b2.add("closet"); b2.add("desk"); b2.add("wardrobe"); System.out.println(b2); Collection b3 = new HashSet(); b3.add("brother"); b3.add("sister"); b3.add("brother"); System.out.println(b3); } // end of main() } b1.size()==2 b3.size()==2 33 Comparing different Sets (1/2) 34 Comparing different Sets (2/2) Output: HASH SET one two five four three seven six LINKED HASH SET one two three four five six seven TREE SET five four one seven six three two 35 Iterators Iterators are objects to navigate over a collection. iterator() method is declared in the interface Collection. It returns an iterator, which is an object of a class implementing Iterator interface. Other methods from the interface Iterator: • Object next(); // returns next element in the collection or raises NoSuchElementException • void remove(); // removes the current element • boolean hasNext(); // obvious 36 Iterators, cont’d ([Barteczko’04]) remove() can be called only once per next(). Typical use: Iterator it = c.iterator(); /* c – any collection implementing Collection */ while (it.hasNext()) { Object o = it.next(); if (removal_condition(o)==true) it.remove(); } Watch this: it.next(); it.remove(); it.remove(); // WRONG // IllegalStateException raised 37 Associative arrays A HashMap object keeps a set of pairs (key, value). Basic methods: put(key, value); // adding a pair get(key); // reading the value “under” the key HashMap m = new HashMap(); m.put("John Smith", "Ferrari"); m.put("James Bond", "Aston Martin"); m.put("Stefan Karwowski", "Fiat 126P"); System.out.println("James Bond drove " + m.get("James Bond")); 38 New language features since J2SETM 5.0 • generics (somewhat similar to templates in C++), • varargs (enables methods to receive variable numbers of arguments) – discussed in Lecture #1, • enhanced for loop, • boxing / unboxing conversions, • static imports, • enums. 39 Generics When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection inconvenient and unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time. With generics, the compiler will know the object type (same for all objects stored), so that it can be checked. 40 Nice wittisism from [ http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html ] When we declare c to be of type Collection<String>, this tells us something about the variable c that holds true wherever and whenever it is used, and the compiler guarantees it (assuming the program compiles without warnings). A cast, on the other hand, tells us something the programmer thinks is true at a single point in the code, and the VM checks whether the programmer is right only at run time. 41 Defining generics [ http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf ] Small excerpt from the definitions of the interfaces List and Iterator in package java.util: public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); } Might seem very similar to C++ templates so far... 42 ...But it is different than C++ templates In C++, templates are kind of intelligent macros. Having vector<int> and vector<double> in our program, we also have two copies of the code: a single copy for each used type (=template parameter). In other words, it is a compile-time mechanism. Not so in Java. There aren’t multiple copies of the code: not in source, not in binary, not on disk and not in memory. An analogy to plain methods: parameters in methods are values of a given type; parameters of generics are types. A method has formal value parameters that describe the kinds of values it operates on; a generic declaration has formal type parameters. When a method is invoked, actual arguments are substituted for the formal parameters, and the method body is evaluated. When a generic declaration is invoked, the actual type arguments are substituted for the formal type 43 parameters. Consequently... ...the following piece of code: List <String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getClass()); ...prints true. 44 Enhanced for The for loop now works with collections and arrays naturally. New for: for (Object o: someCollection) { System.out.println(o); } for (String s: someStringArray) { System.out.println(s); } Compare the ugliness of the old form: 45 Enhanced for, cont’d Same code examples using the new for: The new for idea is equiv. to foreach loop in some other languages (C#, Perl, PHP). But the Java designers chose not to introduce a new keyword. 46 Old for, find a bug! [ http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html ] 47 Enhanced for, final words [ http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html ] Unfortunately, you cannot use the for-each loop everywhere. Can’t use it when your code accesses to the iterator (e.g., in order to remove the current element). The for-each loop hides the iterator, so you cannot call remove. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. 48 (Auto)boxing [ http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html ] You can’t put an int (or other primitive value) into a collection. That is, you must convert it to Integer (object type) first. It is called boxing a primitive value into a wrapper class instance. Or the other way round: when you take an object out of the collection, you get e.g. an Integer that you’ve put it; if you need a primitive (i.e. an int in our case), you must unbox the Integer using the intValue method. Good news: a new language feature eliminates the pain and the clutter. 49 Autoboxing example (based on [W. Clay Richardson et al., Professional Java, JDK 5 Edition, Wrox, 2005]) Or another example (with generics): HashMap<String,Integer> hm = new HashMap<String, Integer>(); hm.put("speed", 20); 50 Static imports [ http://www.agiledeveloper.com/articles/Java5FeaturesPartII.pdf ] import statement gives a hint to the compiler as to which class you are referring to in your code. Convenient: type JButton instead of javax.swing.JButton. Of course if classes in multiple package/namespace collide, then we will get an error. In this case, you can resort to using the fully qualified name for the class. New in Java 5.0: not only a fully qualified class name can be omitted, but also the class name in front of static methods! E.g. can use abs() instead of Math.abs(). 51 Static imports, example [ http://www.agiledeveloper.com/articles/Java5FeaturesPartII.pdf ] We are making a call to abs(), ceil(), and getRuntime() as if these are static methods of the Test class (which they are not). The static import gives us the impressions that we have brought 52 these methods into the current namespace. Enumerated types (enums) An enumerated type: a user-defined type which explicitly enumerates all the possible values for a variable of this type. Example (C++): enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}; Some other languages (Pascal, Ada, C#...) also have enums. In Java – workarounds were needed until recently... Enum benefits: type safety, code clarity, compact declaration, no run-time performance penalty. 53 Enums in Java (5.0+)... ...are better than in e.g. C++. Basic use and syntax is alike: enum Season { WINTER, SPRING, SUMMER, FALL } The Java enum is a special type of class (dubbed an enum type). It allows you to add arbitrary methods and fields, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods (equals(), compareTo()...). 54 More on enums All enumerations implicitly subclass a new class: java.lang.Enum. It implements the Comparable and Serializable interfaces. Java introduces two new collections, EnumSet and EnumMap, which are only meant to optimize the performance of sets and maps when using enums. Enumerations can be used with the existing collection classes, or with the new collections when optimization tailored to enumerations is desired. (You could use a more general HashMap with enums too. But it may be not so efficient.) 55 Enum with fields and methods, example ([W. Clay Richardson et al., Professional Java, JDK 5 Edition, Wrox, 2005]) enum ProgramFlags { showErrors(0x01), includeFileOutput(0x02), useAlternateProcessor(0x04); private int bit; ProgramFlags(int bitNumber) { bit = bitNumber; } // constructor public int getBitNumber() { return(bit); } } public class EnumBitmapExample { public static void main(String[] args) { ProgramFlags flag = ProgramFlags.showErrors; System.out.println("Flag selected is: " + flag.ordinal() + " which is " + flag.name() ); } } // ordinal() returns the position of the constant in the list (from 0) 56 Intro to I/O Basic classes for reading and writing sequences of bytes are FileInputStream and FileOutputStream. When we create a file object (eg. of any of the two just mentioned classes), the file is open. FileInputStream inp = new FileInputStream("1.dat"); FileOutputStream outp = new FileOutputStream("2.dat"); Read a byte, write a byte: int read(); write(int); Read value –1 signals the end of file. 57 Byte-by-byte copy example ([Barteczko’04]) 58 Don’t forget exception handling Long code..? Yeah, the previous example won’t compile without • the try ... catch block(s) • or the line static public void main(String[] args) throws IOException Text I/O What’s the difference...? Code pages. If we read eg. Polish text in CP-1250 and copy it to another file with FileInputStream / FileOutputStream classes, we’re likely to lose information. 59 Text I/O, cont’d Use FileReader, FileWriter classes. FileReader: converts from the default codepage to Unicode. FileWriter: the other way around... import java.io.*; public class ReadByReader { public static void main(String[] args) { StringBuffer cont = new StringBuffer(); try { FileReader inp = new FileReader(args[0]); int c; while ((c=inp.read()) != -1) cont.append((char)c); inp.close(); } catch(Exception e) { System.exit(1); } String s = cont.toString(); System.out.println(s); } } 60 Object I/O [ http://www.cs.stir.ac.uk/courses/31V4/lectures/java5.pdf ] In Java, there exists a powerful mechanism for storing arbitrary objects in files (e.g., on disk). Or, more generally, sending them to a stream. We save objects and then can recover them. This uses object serialization. Basically, we can use methods writeObject() and readObject() – for any objects. myOutFile.writeObject(thisObject); val = (MyClass)myInFile.readObject(); // casting necessary 61 Object I/O, cont’d [ http://www.cs.stir.ac.uk/courses/31V4/lectures/java5.pdf ] We shall use classes derived from OutputStream and InputStream: OutputStream FileOutputStream ObjectOutputStream InputStream FileInputStream ObjectInputStream Import them from java.io. 62 Object I/O, getting started... [ http://www.cs.stir.ac.uk/courses/31V4/lectures/java5.pdf ] For output: ObjectOutputStream out; out = new ObjectOutputStream ( new(FileOutputStream("myFile.dat") ); // use out.writeObject(...) out.close(); For input (say, we read from the same file): ObjectInputStream inp; inp = new ObjectOutputStream ( new(FileOutputStream("myFile.dat") ); // use inp.readObject() inp.close(); 63 Object serialization [ http://www.cs.stir.ac.uk/courses/31V4/lectures/java5.pdf ] writeObject() is powerful. It converts an object of any class into a bit sequence and then sends it to a stream, in a way that it can be subsequently retrieved (using readObject()) as an object of the original class. Not surprisingly, static fields are NOT written to the stream. Serialized objects may contain e.g. other objects as their fields. No problem with e.g. arrays either. Even multi-dim arrays (btw, in Java a 2-d array is, formally speaking, an array of arrays). 64 How to serialize our own class [ http://www.cs.stir.ac.uk/courses/31V4/lectures/java5.pdf ] Our class must simply implement the interface Serializable. public class Tank implements Serializable { ... } ...And now, already, a Tank can be sent to a file with writeObject(), and retrieved with readObject(). Isn’t it magic?! An object is stored binary (you can peek it with eg. MS Notepad or some hex viewer, and see). 65 Casting required [ http://www.cs.stir.ac.uk/courses/31V4/lectures/java5.pdf ] When we read an object with readObject(), what we get is actually an object of the class Object(). Cast examples: Student s = (Student)inpFile.readObject(); int[] tab = (int[])inpFile.readObject(); 66 Another complication... [ http://www.cs.stir.ac.uk/courses/31V4/lectures/java5.pdf ] The method readObject() may throw a ClassNotFoundException. What is more, the compiler requires such exceptions to be either caught or thrown. Two ways to handle this, of course: • either try ... catch block • or the method that calls readObject() must throw ClassNotFoundException. 67 Serializable interface is empty It has no methods. Such interfaces simply make possible to check a data type, e.g. with instanceof operator. That’s what the writeObject(...) method does: checks if x instanceof Serializable == true. If the condition is met, it sends the object to a stream, otherwise it doesn’t. 68 java.util.zip (compressed I/O) The package java.util.zip contains several classes for data compression / decompression. A few class examples: Deflater – in-memory compression using zlib library Inflater – in-memory decompression using zlib library GzipOutputStream – compresses data using the GZIP format. To use it, construct a GZIPOutputStream that wraps a regular output stream and use write() to write compressed data GzipInputStream – like above, but for reading data ZipOutputStream, ZipInputStream – I won’t offend your intelligence ZipEntry – represents a single element (entry) in a zip file 69 Compression example (using gzip format) [ http://www.cafeaulait.org/slides/intljava/2001ny/javaio/44.html ] Writing to a stream of GZipOutStream type. Which means it’ll be compressed on-the-fly. 70 ZipFile class [ http://www.supinfo-projects.com/fr/2005/ ] Used to read the entries in a zip file. In order to create or to read these entries, you have to pass a file as argument to the constructor: ZipFile zipfile = new ZipFile(new File("c:\\test.zip")); This instantiation can throw a ZipException, as well as IOException. One of the solutions is to surround it in a try/catch: try { zipfile = new ZipFile(new File("c:\\test.zip")); } catch (ZipException e) { } catch (IOException e) { } Now, files in a zip can be e.g. listed. 71 Listing a zip file [ http://javafaq.nu/java-example-code-225.html ] 72 File class Representation of a file or directory path name. This class contains several methods for working with the path name, deleting and renaming files, creating new directories, listing the contents of a directory, etc. File f1 = new File("/usr/local/bin/dog"); File f2 = new File("d:/my_pets/cat1.txt"); File f3 = new File("cat.txt"); File g = new File("/windows/system"); File h = new File(g, "rabbit.gif"); File i = new File("/windows/system", "rabbit.gif"); // objects h and i refer to the same file! 73 File class, cont’d Selected methods (1/2) boolean canRead() // Returns true if the file is readable boolean exists() // Returns true if the file exists boolean isDirectory() // Returns true if the file name is a directory boolean isFile() // Returns true if the file name // is a "normal" file (depends on OS) long length() // Returns the file length boolean setReadOnly() // (since 1.2) Marks the file read-only // (returns true if succeeded) boolean delete() // Deletes the file specified by this name. boolean mkdir() // Creates this directory. // All parent directories must already exist. 74 File class, cont’d Selected methods (2/2) String[] list() // Returns an array of Strings with names of the // files from this directory. Returns null if not a dir. String[] list(FileNameFilter filter) File[] listFiles() File[] listFiles(FileFilter) File[] listFiles(FileNameFilter) // (all three since 1.2) FileFilter: public interface with only one method: boolean accept(File pathname); // tests if the specified pathname should be included in a pathname list FileNameFilter: similar interface but the arg list for accept() different 75 Why doesn’t it work? [ http://www.csc.uvic.ca/~csc330/ ] There is a requirement in the Java type system: the elements of an array all have types which are compatible with the type of array that was instantiated. Variable b is assigned a value of type String[]. It is therefore illegal to assign an incompatible value to an element of that array. 76