Вы находитесь на странице: 1из 36

Questions and Answers from Collections How do I get the list of system properties that tell me things like

which version of Java a user is running and their platform-specific line separator? The System.getProperties() method will return the standard property set.

How do I get the length of an array? To avoid getting an ArrayIndexOutOfBoundsException, you can check for the array length from either the length instance variable or using reflection and calling java.lang.reflect.Array.getLength(), passing the array as an argument to the method. int length = args.length;// If args is a reference to an array type, use args.length. // or int length2 = Array.getLength(args); // when args is a generic Object reference and args.getClass().isArray() is true

How do I print a Collection The Collection Framework implementation classes override the toString() method to print out all the elements of the collection. If you create your own custom implementation, as long as your class is a subclass of AbstractMap or AbstractCollection you'll inherit this behavior. (Keep in mind that AbstractList and AbstractSet subclass AbstractCollection.) public static void print(Collection c) {
for(Iterator i = c.iterator(); i.hasNext(); ) System.out.println(i.next()); }

How do I use an array with the Collections Framework The Arrays.asList() method provides a fixed-length List view of an array, where changes to the List are stored in the original array. The Arrays class also provides additional support methods for sorting and searching an array.

Which of implementation of List have better performing for add(i) and remove(i) method ArrayList or LinkedList? Linked List, because in case of array list some elements need to move up where as in case of linked list it just changing some references.

For random access, which implementation is better, ArrayList or LinkedList and why? ArrayList is better because it is implemented using array and access is thru index of array where as in case of LinkedList we need to traverse thru as many elements of index.

If a hashMap has 100 entries and another has 1000000 entries, get and put will be faster in which case and why? Hashmap is implemented using array of

Entry object. To get an value for some key, first index in the array is calculated using hash code and then direct access to array is made. What is difference between using iterator and for loop for accessing member of some collection? Iterator provides fail safe access to collection. If another thread modify under lying collection, iterator throws ConcurrentModificationException.

How do you store a primitive data type within a Vector or other collections class? You need to wrap the primitive data type into one of the wrapper classes found in the java.lang package, like Integer, Float, or Double, as in: Integer in = new Integer(5);

How do I make an array larger? You cannot directly make an array larger. You must make a new (larger) array and copy the original elements into it, usually with System.arraycopy(). If you find yourself frequently doing this, the Vector class does this automatically for you, as long as your arrays are not of primitive data types.

How do I use Enumeration to iterate through a collection? Enumeration enum = ...; while (enum.hasMoreElements()) { Object element = iterator.nextElement(); // process element } How do I sort objects into their reverse natural ordering? The Collections.reverseOrder() method returns a Comparator that sorts objects that implement the Comparable interface in reverse order. What is difference between Iterator and ListIterator? List iterator allow to move back ward also using previous() method how can we store elements in arraylist? as by using index or by node? We can store elements in arraylist by using index. The interface that ArrayList implements is List.The method that is availble in List interface isObject add(int index , Object element); 2)or the interface that List interface implemets is Collection.The method that is available in Collection is :-boolean add(Object element); Why doesn't the Iterator interface extend the Enumeration interface? If the Iterator interface extended the Enumeration interface, the Iterator interface would end up with five methods where two methods just called other methods in the interface. The designers of the framework wanted to get rid of the cumbersome Enumeration method names so had the Iterator interface stand on its own with new shorter method names.

What is a weak reference and what are they used for? Normally the Java garbage collector plays safe. It will only free up the memory used by an object when that object can no longer be accessed by the program. Once an object become impossible to reach it is eligible for collection, and eventually its memory will be reclaimed. This eliminates one of the most common programming errors in some other languages (like C++), where code accidentally tries to access an object that has been freed. Unfortunately it can lead to another problem, where you leave open a potential access route to an object that you don't need any more. Memory fills up, and the program slows down or reports an "Out of Memory" error. To avoid this, you can be very careful to close off access paths to an object once you have finished using it. Java 2 introduces another alternative, the weak reference. Weak references provide access to an object without preventing it from being freed. When you use a weak reference you have to accept that the object referred to may have disappeared, which results in the reference being automatically set to null. On the other hand, the weak reference will not hold the object in memory once it is inaccessible via normal references (or via "soft" references - see below). Weak references are not appropriate in all circumstances, but sometimes they can make code easier to write and understand. The most common use of weak references is indirect - they are used internally by the WeakHashMap class. Like HashMap, WeakHashMap associates key objects with values. However, once the key object becomes inaccessible via stronger references it becomes eligible for garbage collection. When it is freed, the map entry magically disappears. The assumption here is that if you are not using the key anywhere other than in the map you will have no need to look it up, so it should be freed. Other specialist references are soft references (which inhibit collection until memory runs short), and phantom references (used for cleanup when objects are freed). Can HashMap store null values?If yes, how many and in which one? yes, HashMap can store null values. u can have new HashMap("a",null); also key can be null ie new HashMap(null,null); value can be retrieved by get method ie get(null) returns null. hashmap accepts null values. we can set null values by put method & get the values by get method put(null,null) There can be mutiple null values present in a HashMap. Restriction is on keys which should be unique. HashMap allows only one null key. If we put more with key null, it replaces previous value with new value.

You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList? ArrayList Is Iterator a Class or Interface? What is its use? Iterator is an interface which is used to step through the elements of a Collection.

I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere? The existing object will be overwritten and thus it will be lost. Can a vector contain heterogenous objects? Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

Can a ArrayList contain heterogenous objects? Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object. What is the difference between Comparable and Comparator ?
The Comparable is for natural ordering and Comparator is for custom ordering. But we can override the compareTo method of comparable interface to give a custom ordering.

If aaaa is an array then why aaaa.length why not aaaa.length()?


length is a property not a

Because

method

What is HashMap and Map?


implements that.

Map is Interface and HashMap is class that

What is hash-collision in Hashtable and how it is handled in Java? - Two


different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.

What is the major difference between LinkedList and ArrayList? - LinkedList


are meant for sequential accessing. ArrayList are meant for random accessing.

What are the differences between Collection, Collections, and Java collections framework?Java Collections Framework: A generic name given to Java API of collections classes/interfaces in java.util package.Root interfaces of this API are Collection and Map. Collection and Map: are Root interfaces Collections and Arrays: Two classes with all static utility methods. They are NOT interfaces What is a WeakHashMap? What is its use and when should you use it? A WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference. By storing the keys in a weak reference, keyvalue pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren't used elsewhere may be dropped with no side effects. A good example of WeakHashMap in action is the ThreadLocal class. ThreadLocal uses a WeakHashMap internally where the keys are Threads. When you call get(), the ThreadLocal class gets a reference to the current thread and looks up its value in the WeakHashMap. When the thread dies, it becomes unreachable and the WeakHashMap automatically removes its mapping. If ThreadLocal used a regular HashMap, then the Threads stored in it would never become unreachable and they could hang around for a long, long time. This would essentially be a memory leak. How can I implement a List (ordered collection) that keeps an index (i.e. a Map) of its contents? You can't. Each of the Map and List interfaces define a

remove(Object o) method. Each method returns a different type ( Map returns an Object while List returns a boolean). Because the compiler doesn't permit overloaded

methods that differ by only return type, you cannot create a class that implements both the List and Map interface. If you need a Map that maintains insertion order, see the LinkedHashMap added in Java 1.4. I've got open-source code that solves this, in two different classes. My EntryList is a List that stores key-value pairs; it adds get(Object key) and put(Object key, Object value) and a few other methods to the standard ArrayList. My IndexedList is a normal List that builds an index of its contents based on a callback function you pass it - so, for example, if storing Person objects, you could provide a callback that calls getName() for the index. Both of my Lists also have a toMap() method which returns a true java.util.Map object for you to play with Since Properties extends Hashtable, can I use the Hashtable methods to add elements to a Properties list? Technically speaking you can. However, you have to make sure you only add key-value pairs where both are strings. If you add something other than a String, the listing, loading, and saving methods won't work as expected. Like the Stack/Vector subclass relationship, Properties/Hashtable should be a has-a relationship, not an is-a/subclass relationship. When did Strings start caching their hash codes Starting with the 1.3 release of Java, the java.lang.String class will only calculate the hashcode once, when its first needed. Future calls to hashCode() will return the previously calculated value What is meant by compatible equals() and hashCode() methods? In order for the Java Collections to work properly (and everything else in Java), the equals() and hashCode() methods must be compatible. Here, compatible means that if equals() reports that two instances are the same, then the hashCode() of both instances must be the same value. What is the function of a load factor in a Hashtable? The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put). How to sort the messages in JavaMail? Within the JavaMail classes there is no support for this. However, once you get the array of messages back from a folder, you can call the Arrays.sort() method in the collections framework to sort the messges. Since MimeMessage doesn't implement Comparable, you'll need to provide your own Comparator specifying how you want the messages to be sorted. How do you control growth of vectors when their internal arrays are full? The vector constructor can include either an initial capacity or a capacity and growth

increment. When not specified, the initial size of the vector is 10 and growth will double when necessary. What are the differences between Vector and ArrayList? Which is best to use? Vector and ArrayList are very similar. Both of them represent a 'growable array', where you access to the elements in it through an index. The main difference is that Vector it's a synchronized object, while ArrayList it's not.Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList. Synchronization Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily? Data growth Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Usage patterns Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time -- O(1). However, adding and removing elements from any other position proves more expensive -- linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean? It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time -- O(1). How does ArrayList increase its capacity? Unlike Vector where you can specify a capacity increment, ArrayList doesn't support this. Instead, ArrayList will increase capacity by about a half when it runs out of space. The refernece implementation uses the forumla: newCapacity = (oldCapacity * 3)/2 + 1 though, this isn't part of the class definition so others can implement it differently. Can i limit the initial capacity of vector in java? Ya u can limit the initial capacity we can construct an empty vector with specified initial capacity public vector(int initialcapacity) What method should the key class of hashmap override? To help find out the unique the key. the methods to over ride are equals() and hashCode(). How do you sort the elements of a vector? Since the Vector class implements the List interface, you can call the Collections.sort() method to sort the elements in place. Of course, if keeping sorted access is such a big deal, you should consider using a different, more appropriate data structure like a TreeSet.

What are the differences between ArrayList and LinkedList? An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access. With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position. What are the differences between ArrayList and a Vector? the basic differences are Vector allows synchronized way of accessing the elements. where as arraylist allows elements to be made synchronized as well asynchronized. its is dynamic collectiion. u have more flexibilty of using the arraylist collection Both represent growable array of objects. The difference is Vector is Synchronized and Arraylist is not. One Difference between Vector and ArrayList is In vector the data is retrive through elementAt() method while in ArrayList through get() vector has two advantages,first they can dynamically grow and second its method are synchronized.so if more then one object want to access your vector,no inconsistancy will appear 1) Arraylist is not synchronized while vector is. 2. Arraylist has no default size while vector has a default size of 10. what is difference between array & arraylist? arraylist is resizable where as using array it is not possible. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects.It is growable. Array is collection of similar data items.We can have array of primitives or objects. It is of fixed size,We can have multi dimensional arrays. array: it is of fixed length,we can give only a specific data type values;arraylist:it is resizable(dynamically its size increases). It stores objects(not data type values) Array needs to define size; while ArrayList is a resizable. When the vector object doubles it's size? when the size of the vector is full .Try to avoid the old Vector class. Use the List implementations (LinkedList, ArrayList). If you need them to be synchronized wrap them using Collections.synchronizedList(...). Much better performance this way.. how to make immutable collection? U can do this by using the following method available in Collection static Collection unmodifiableCollection(Collection c) it will return u an immutable collection. What are exactly mean by legacy ??i.e; what are legacy classes?? legacy means synchronization.It is the concept of collection framework (utill package).for example: vector , HashTable, etc are legacy classes( synchronized classes)Synchronized classes gives concept of thread safe means if so many request is coming to access a single resources then it will lock all request except first request and will do process one by one with sequence order (FIFO) Differences between HashList and HashMap, Set and List? Hashtable is synchronised and Hashmap is not. List allow duplicate entries but Set does not allow. Hashmap allows null values as key but Hashtable does not. List can store ordered elements and duplicates. Set can't allow duplicates and the order is unordered. HashMap is same as HashTable except that it is not Synchronized and allow null

values. List is an ordered collection and it allow nulls and duplicates in it. Set doesn't allow duplicates, it may allow nulls.A Hashtable is synchronized . but HashMap is
not synchronized. null values. Hashtable does not allow null values , but HashMap allows

Q.What are the differences between HashMap and Hashtable? Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2. The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know. And, a third difference is that HashMap permits null values in it, while Hashtable doesn't. For new code, I would tend to always use HashMap. 1)Synchronized means only one thread can modify a hash table at one point of time.Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. 2)Fail-safe is relevant from the context of iterators.If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally",a concurrent modification exception will be thrown.It is possible for other threads though to invoke "set" method since it doesnt modify the collection "structurally".However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown

How to Synchronize the HashMap? Collections.getSynchronizedMap(HashMap) Map m = Collections.synchronizedMap(new HashMap(...)); How can u tell HashTable is Synchronized?HashTable is Synchronized, at a time only one thread or process can take up the HashTable object instance and do the modifications and other process. Hashtable is not synchronized This example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = 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); }

What is a fail-fast iterator? An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions: 1. In multithreaded processing: if one thread is trying to modify a Collection while another thread is iterating over it.

2. In single-threaded or in multithreaded processing: if after the creation of the Iterator, the container is modified at any time by any method other than the Iterator's own remove or add methods. List list = new ArrayList(); list.add("Peter"); list.add("Paul"); list.add("Mary"); Let's say we wish to iterate over this list. We'd need to declare a ListIterator as follows: ListIterator iter = list.listIterator(); while(iter1.hasNext()){ String str = iter1.next(); // do something with str } Because iter is fail-fast, we are not allowed to invoke List's add or remove methods inside the loop. Inside the loop, we are only allowed to use ListIterator's add and remove methods. This makes sense because it is the Iterator object that knows where it is in a List as the List is being scanned. The List object itself would have no idea of that. The Iterators supported by all the work-horse container classes, such as ArrayList, LinkedList, TreeSet, and HashSet, are fail-fast. The Iterator type retrofitted to the older container class Vector is also fail-fast. For associative containers, such as HashMap and the older HashTable, the Iterator type for the Collections corresponding to either the keys or the values or the <key, value> pairs are fail-fast with respect to the container itself. That means that even if you are iterating over, say, just the keys of the container, any illegal concurrent modifications to the underlying container would be detected. One final note regarding iterators versus enumerations: It is also possible to use an Enumeration object returned by the elements() method for iterating over the older container types such as Vector. However, Enumerations do not provide a fail-fast method. On the other hand, the more modern Iterator returned by a Vector's iterator() and listIterator() methods are fail-fast. Hence, iterators are recommended over enumerations for iterating over the elements of the older container types. Is there a way to create a homogenous collection in Java?How do I make a collection where all the elements within it are a specific data type? You can wait for Generics to be added to Java What's the fastest way to traverse all the elements of a Vector? There are at least four ways to traverse through all the elements of a Vector: Using a for loop and accessing each element with elementAt(index) or get(index) Using an Emumeration Using an Iterator If I have a ArrayList, how can I make access to it as thread safe? Collections.syncronizedCollection(Collection) or Collections.syncronizedList(List) What interface do you implement to do the sorting? - Comparable

How can I sort elements of array list based on some criteria? Define a Comparator that define that criteria, and use Collections.sort(List, Comparator) How can I make an ArrayList un modifiable or immutable? Use Collections.unModifiableList(List) Which collection class you will use to implement queue (FIFO) kind of functionality? LinkedList How will you sort an array of int or long? Array.sort() Why ArrayList is faster than Vector? ArrayList is faster than Vector, because ArrayList is not synchronized. Synchronization will reduce the performance of Vector. Syncronisation Mechanism is more important in Vector class and b'caz of that speed of Vector reduces and Arraylist is not Syncronized and hence faster. Which collections in Java are synchronized and which aren't? The original collection classes in Java are all synchronized: Vector and Hashtable, along with their subclasses Stack and Properties. Those classes introduced with the Java 2 Collections Framework are all NOT synchronized by default, the sets, lists, and maps. If you need to synchronize those I can print my HashTable and obtain a string. Can I reverse the process? All Java Object has a toString() method. They are not supposed to be reversable unless you design your own. If we want to store a key value pair where the same key may have more than one value which collection can we use (is there one for this situation ?) You cannot have directly multiple values for a key. Anyhow there is a work around for this. You can have an array or arraylist which contains multiple values and put this arraylist in the map with a key. Like this you can have mulitple values with a single key. What is the difference between Enumeration and Iterator?. When i can use Enumeration and when i can use iterator?. Can any one tell me the situation that only Enumeration could able to solve that problem and vice versa. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.So Enumeration is used when ever we want to make Collection objects as Read-only.ie.In Enumeration we cant modify the elements. where as in iterator we can modify the elements The functionality of Enumeration interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names.ie Iterator has a remove() method while Enumeration doesn't. Both are used to traverse objects one by one. Enumeration can be used for Collection objects as well as Iterator can be used for legacy classes. Enumeration and Iterator both are interfaces present in util package. Enumeration is a legacy interface which does not come under the collection framework, wheras Iterator is an interface present in the collection framework. All the legacy classes like Stack, Vector , Hashtable, Properties can use Enumeration for enumerating

10

the elements from the collection. The classes under the collection framework like ArrayList, LinkedList, HashSet ,Tree Set etc can use the Iterator interface. Both are used to travel objects one by one, But Enumeration is a leagsy classes and it comes with java1.1, Iterater they have introduced in Collection framework. Enumeration deals with objects while iteration deals with values only . Enumeration is used when we use vector, hashtable, etc while iteration are used in while loop, for loop etc. Enumeration can be used for Collection objects as well as Iterator can be used for legacy classes. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. Both are used go through the collection objects. Enumeration is read only. we can't change the object or value in the collection.we have only forward facility.we have two type of Iterators those are Itrator and ListIterator Using of the iterator we can remove the objects form the collection. Using of the listIterator we can go forward and privious in the collection objects Enumerations Another way to step through elements of a vector is with an Enumeration. An Enumeration is an interface with two methods: public abstract boolean hasMoreElements() public abstract Object nextElement() You can create an enumeration from a vector with the elements method: public final synchronized Enumeration elements() Here is how you might use it in the above example: class vector4 { public static void ShowVector(Vector v) { String str; Enumeration enum; enum = v.elements(); while (enum.hasMoreElements()) { try { Thread.sleep(100); } catch (InterruptedException e) {} str = (String)enum.nextElement(); System.out.println(str); } } Q. What is meant by natural ordering of objects in the context of the collections framework? By the specifications of the interfaces such as SortedSet, SortedMap, etc., and the data structures used for container classes such as TreeSet, TreeMap, etc. Unless

11

instructed otherwise via a Comparator object supplied as an argument to the constructor, the default behavior of a class such as TreeSet is to store its objects in an ascending natural order. The objects of a class exhibit natural ordering if the class has implemented the java.lang.Comparable interface. Such a class must provide an implementation for the compareTo method -- referred to as the class's natural comparison method -- that can then be used by the algorithms and the data structures for comparing data objects. The compareTo method must return a negative integer, a zero, or a positive integer if the object on which it is invoked is less than, equal to, or greater than the argument object. It is strongly recommended that a class's natural ordering as dictated by the implementation of the compareTo method be consistent with equals. This consistency is achieved if and only if e1.compareTo( (Object) e2 ) == 0 has the same boolean value as e1.equals( (Object) e2 ) for every pair of objects e1 and e2 of the class. Lack of this consistency could elicit strange behavior from the data structures that need to compare objects. Many of the system supplied classes possess natural ordering. These include String, Integer, Float, Double, Date, File and many others. For the String class, the natural order is lexicographic; it is chronological for the Date class; lexicographic on the pathname for the File class, etc. What's the purpose of the IdentityHashMap? The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another In a TreeMap, can I use a sorting algorithm other than the natural sorting for the keys? You can pass a Comparator to the TreeMap constructor to use a sorting order other than the natural order. What's the most optimum way of swapping two elements in a List? The 1.4 version of Collections has a swap() method to do this for you. However, for earlier version of Java, you can swap two elements w/o an intermediate variable with: list.set(index1, list.set(index2, list.get(index1))); How can you get the hash code for an instance of a class if the class overrode hashCode()?The System class method identityHashCode() allows you to get this information: int code = System.identityHashCode(anObject); How do you sort an ArrayList (or any list) of user-defined objects? Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator). Does the equals() method of an array do element-level checking? If you have two arrays in memory with the same elements, and ask first.equals(second), this does not do an element-by-element comparison. Instead, it behaves just like Object's equals() method, essentially asking if the variables point to the same place in memory: int a[] = {1, 2, 3}; int b[] = {1, 2, 3};

12

// This prints false System.out.println(a.equals(b)); To check for equality of two arrays, use Arrays.equals(). // This prints true System.out.println(Arrays.equals(a,b)); How do I make a copy of an array? The arraycopy method of System allows you to do this but... starting in Java 6, there is a new copyOf() method added to the Arrays class that is slightly more flexible. How do I sort an array? If the array is an array of primitives or an array of a class that implements Comparable then you can just call the method directly: Arrays.sort(theArray); If, however, it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array. Arrays.sort(theArray, theComparator); Which is the preferred collection class to use for storing database result sets? When retrieving database results, the best collection implementation to use is the LinkedList. The benefits include: Retains the original retrieval order Has quick insertion at the head/tail Basically: ResultSet result = stmt.executeQuery("..."); List list = new LinkedList(); while(result.next()) { list.add(result.getString("col")); } Which is faster, synchronizing a HashMap or using a Hashtable for threadsafe access? Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access. What is the difference between a Stack and a Queue? difference is that one is a concrete implementation (Stack) while the other is an interface (Queue) Java's Stack class extends the Vector class. A Stack represents a Collection of objects that are in LIFO (Last In First Out Order). boolean empty() Tests if this stack is empty. E peek() Looks at the object at the top of this stack without removing it from the stack. E pop() Removes the object at the top of this stack and returns that object as the value of this function. E push(E item) Pushes an item onto the top of this stack. int search(Object o) Returns the 1-based position where an object is on this stack. A Queue is also a Collection of Objects similar to a Stack. Queues typically order the elements contained within in FIFO Besides how each order their elements there really isn't much difference. Both provided pretty much the same operations. Do the keys() and elements() methods of a Hashtable enumerate things in the same order?

13

if you can use a HashMap instead of a Hashtable, work with the Map.Entry that is returned by the keySet(). This includes both the key and value together, not requiring a separate lookup. What are Generics and how can I use them? So you might ask. What are Generics and why should I use them? Generics are a way to restrict a data structure to hold only a specific type thus providing compile time type checking. One of the added bonuses is that it is no longer necessary to cast a returned Object to a specific type because the compiler is aware of what type is being held by the Collection and what type is to be returned. Set s = new SortedSet(); s.add(new String("Java")); String j = (String) s.get(0); // cast required; // java 5 Set<String> s = new SortedSet<String>(); s.addElement(new String("String Type")); String s = s.get(0); // no cast required! Having a type safe system not only obviates the need to cast to a specific type but shields the programmer against miss-casting or casting to an unrelated type at runtime. String s = "Java, write once run anywhere"; List l = new ArrayList(); l.add(new String("Java")); Integer i = (Integer)l.get(0); // Runtime exception! ClassCastException! // Using Generics the compiler catches String s = "Java. Write once run anywhere!"; List<String> l = new ArrayList<String>(); l.add(new String("Java")); Integer i = l.get(0); One of the biggest additions since the creation of the Collections framework is Generics.. A generic type is defined using one or more type variables with it's contained methods using that type variable as a place holder to mark a parameter or return type. For instance the interface List has now been defined as. public interface List<E>{ public add(E e); Iterator<E> iterator(); } public interface Iterator<E>{ E next(); boolean hasNext(); } What happens if two threads perform a get of one hashmap at the same time? Synchronization needs to be done only when there is a chance of changing the data from different threads simultaneously. In your case, it is simply going to be a read, the synchronization is not required. If you need to remove or modify the values in the hashmap, then you [may] need to synchronize that.

14

For synchronizing a HashMap, you can use Collections.synchronizedMap(<your hashmap reference>) which will return a synchronized map for you, which is threadsafe. Remember, synchronization will cause a performance problem. So, it needs to be used carefully, when really required. How do I synchronize a collection? With the Collections Framework, the new implementations are all unsynchronized by default. If you need synchronized access, you must synchronize things yourself. The Collections class offers a wrapper method for each of the six core collection interfaces that add synchronization to an arbitrary collections implementation. To ensure threadsafety, direct access to the original backing collection must be avoided. list = Collections.synchronizedList(list); It is imperative that the user manually synchronize on the returned collection when iterating over it: Collection c = Collections.synchronizedCollection(myCollection); ... synchronized(c) { Iterator i = c.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); } What's new to the Collections Framework in Java 1.4? There are three new implementations: LinkedHashSet LinkedHashMap IdentityHashMap One marker interface: RandomAccess And six new utility methods for the Collections class: rotate(List list, int distance) replaceAll(List list, Object oldVal, Object newVal) indexOfSubList(List source, List target) lastIndexOfSubList(List source, List target) swap(List list, int i, int j) list(Enumeration e)

Is Vector's clone method thread-safe? Sure it is, since it is a Vector which is thread-safe. How can I add an array of objects to a collection? First you need to convert the array to a Collection. This can be done with Arrays.asList(objectArray). Once you have the array as a List, you can add it to another Collection with theCollection.addAll(theList). How do I use a ListIterator to go through a List backwards? List list = ...; ListIterator iterator = list.listIterator(list.size()); while (iterator.hasPrevious()) {

15

Object element = iterator.previous(); // Process element } How do I use an Iterator to go through a Collection? Collection collection = ...; Iterator iterator = collection.iterator(); while (iterator.hasNext()) { Object element = iterator.next(); // Do something with element } } What is iterator a class or interface? Usage of Iterator? It is an interface. Iterator it = someCollection.iterator(); While(it.hasNext()) { SomeClass c = (SomeClass)it.next(); } How to print all key and values of hashmap on console? Set keys = map.keySet(); Iterator it = keys.iterator(); While(it.hasNext()) { Object key = it.next(); System.out.println(key + : + map.get(key)); } How do you create a multi-dimensional List? Since the elements of a List are objects, in order to make the List multi-dimensional, each object in the outer list needs to be a List, too. For instance, ... List list = new ArrayList(10); for (int i=0; i<10; i++) { list.set(i, new LinkedList()); } Then just fill up each inner list with items. How do I save properties settings with the Properties class? Properties prop = new Properties(); FileOutputStream output = new FileOutputStream("Test.properties"); prop.store(output,"my testproperties"); output.flush(); output.close(); You'll need to catch an IOException How do I load property settings with the Properties class?

16

java.util.Properties objects can load values from a file using the method load(InputStream). Here is the code you need: Properties props = new Properties(); props.load(new FileInputStream("propertyfile.properties")); String value = props.getProperty("propertyname"); How can I process through the keys of a Hashtable in sorted order? In order to get all the keys for a Hashtable, you use the keys() method to get an Enumeration or the keySet() method to get a Set. If you are using Java 2, and can use the collections framework, what you should do is get the key set of the Hashtable and create a TreeSet from it. You can then get an iterator() from the created TreeSet that will have the keys in order. If you can't use the collections framework, you'll have the sort the Enumeration you get back from keys() yourself. Yes, it does. A TreeSet is, by definition, sorted. So, when you construct a TreeSet passing the constructor a collection, it is sorted. If you would like it spelled out: Iterator it = new TreeSet (someHashtable.keySet()).iterator(); while (it.hasNext()) { YourKeyClass yourKey = (YourKeyClass) it.next(); // Now, you're reading the key objects in the natural sort order... YourValue yourValue = (YourValue) someHashtable.get(yourKey); // Refer to the original Hashtable for the corresponding value... } How does a Hashtable internally maintain the key-value pairs? The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index. How do I look through each element of a HashMap? To go through all the elements of a HashMap, or any class that implements the Map interface, call the entrySet() or keySet() methods than loop through what is returned. The entrySet() returns a group of Map.Entry elements, whereas the keySet() method just returns a Set of key elements. If you then want what the key refers to, you'd have to look them up. Once you have a Set to work with, you would then use an Iterator to go through all its elements. The following demonstrates: Map map = some hash map Set set = map.keySet(); Iterator it = set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } How do I create a read-only collection?

17

The Collections class has six methods to help out here: unmodifiableCollection(Collection c) unmodifiableList(List list) unmodifiableMap(Map m) unmodifiableSet(Set s) unmodifiableSortedMap(SortedMap m) unmodifiableSortedSet(SortedSet s) If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException. How can I define my own Comparable type so that it can be naturally sorted within a List? When taking a peek at the Java docs you will notice certain classes implement an interface named Comparable. Take a look at some of the subclasses of Number such as Byte, Integer, Long, Float or some of the classes like String and Date. What the Comparable interface provides is a way for a class to be sorted by it's natural ordering. So what do we mean by natural ordering? Depending on the type wishing to be sorted the natural ordering can be different things. If we are sorting Strings the ordering is lexicographic or alphabetic if we are sorting Dates the ordering is chronological if we are sorting Integers the ordering is numerical. Comparable only contains one method that needs to be implemented by the class wishing to be sorted naturally. Remember if you try and sort a list that contains elements that do not implement the Comparable interface then Collections.sort() will throw an exception specifically a ClassCastException. public interface Comparable<T>{ public int compareTo(T o); } The following is a short example on how to implement the Comparable interface and use the compareTo(T o) method. import java.util.*; public final class Alpha implements Comparable<Alpha>{ public static void main(String[] args){ List<Alpha> alpha = new ArrayList<Alpha>(); alpha.add(new alpha.add(new alpha.add(new alpha.add(new alpha.add(new alpha.add(new alpha.add(new alpha.add(new alpha.add(new Alpha("z")); Alpha("g")); Alpha("k")); Alpha("q")); Alpha("a")); Alpha("b")); Alpha("o")); Alpha("v")); Alpha("c"));

Collections.sort(alpha); System.out.println(alpha); }

18

private String letter; public Alpha(String letter){ if(letter == null){throw new NullPointerException();} this.letter = letter; } public String toString(){return letter;} public boolean equals(Alpha a){ if(!(a instanceof Alpha)) return false; return letter.equals(a.letter); } public int compareTo(Alpha a){ int i = letter.compareTo(a.letter); return i; } } More complex examples might included sorting on multiple fields. Most things that you would have to sort probably have more then one part like a name for instance (First:Middle:Last) or maybe you have to sort in (Brand:Model) order. import java.util.*; public final class Car implements Comparable<Car>{ public static void main(String[] args){ Car[] cararry = {new Car("Toyota","Celica"), new Car("Honda","Civic"), new Car("Ford","Mustang"), new Car("Lexus","ES"), new Car("Acura","Integra"), new Car("Honda","Accord"), new Car("Acura","RL"), new Car("Toyota","Avalon") }; List<Car> car = Arrays.asList(cararry); Collections.sort(car); System.out.println(car); } private String brand; private String model; public Car(String brand, String model){ if(brand == null || model == null){throw new NullPointerException();} this.brand = brand; this.model = model; } public String toString(){return brand + " " + model;} public boolean equals(Car car){ if(!(car instanceof Car)) return false; boolean samebrand = brand.equals(car.brand); return samebrand != true ? samebrand: model.equals(car.model); }

19

public int compareTo(Car car){ int i = brand.compareTo(car.brand); return(i != 0 ? i : model.compareTo(car.model)); } } How do I treat an object I get out of a Vector (collection) as the type I put into it? When you get an object out of a Vector (or any collection), the object is returned as being of type Object. You need to cast it back into the object type you put into the data structure if you need to call or treat the object as the original type. For instance, if you add an array to a vector: String args[] = {"1", "2", "3"}; Vector v = new Vector(); v.addElement(args); Then, when you get the object out of the vector, you need to cast it back to the original type: String args2[] = (String[])v.firstElement(); System.out.println(args2.length); How can I create a Collection based on another Collection? Every concrete implementation provides a constructor, which takes a Collection as an argument. Care must be taken when creating a Collection based another Collection, this is because depending on the target concrete implementation being created, specific rules regarding duplicates may be be enforced. Such as creating a Set based on a List. The following is a short list of the constructors provided by some of the concrete Classes of the JCF (Java Collections Framework), which enable the creation of a Collection based an another implementation. ArrayList(Collection<? extends E> c) LinkedList(Collection<? extends E> c) Vector(Collection<? extends E> c) TreeSet(Collection<? extends E> c) Creating a Collection based on another Collection is quite easy. The hard part is knowing which Collection to use based on performance and other issues. For example the ArrayList created will contain the same elements in the same order as the first ArrayList created. List<String> slist = new ArrayList<String>(); slist.add("g"); slist.add("a"); slist.add("d"); slist.add("a"); slist.add("f"); slist.add("e"); slist.add("c"); slist.add("b");

20

for(String s : slist){ System.out.print(s + "\t"); } System.out.println(); List<String> s2list = new ArrayList<String>(slist); for(String s : s2list){ System.out.print(s + "\t"); } When creating a Set based on an existing List the Set will be void of duplicates. List<String> slist = new ArrayList<String>(); slist.add("g"); slist.add("a"); slist.add("d"); slist.add("a"); slist.add("f"); slist.add("e"); slist.add("c"); slist.add("b"); for(String s : slist){ System.out.print(s + "\t"); } System.out.println(); Set<String> s2set = new TreeSet<String>(slist); for(String s : s2set){ System.out.print(s + "\t"); } How can I convert a Collection to an Array then back to a Collection? The Collection interface provides a mechanism to turn a Collection into an Array using the methods <T> T[] toArray(T[] a) or Object[] toArray(). The first method will return a Array containing all the elements of the Collection with the array being that of the type provided in the method call. The second method just returns an array being of an Object[] type. The Arrays class provides the opposite. A way to turn an array into a List using the List<T> asList(Array[] a) method. The List returned is of a fixed length with any attempts to add an element throwing an UnsupportedOperationException . import java.util.*; public class G{ public static void main(String[] args){ List<String> sun = new ArrayList<String>(); sun.add("Feel"); sun.add("the"); sun.add("power"); sun.add("of"); sun.add("the"); sun.add("Sun"); String[] s1 = sun.toArray(new String[0]); //Collection to array

21

for(int i = 0; i < s1.length; ++i){ String contents = s1[i]; System.out.print(contents); } System.out.println(); List<String> sun2 = Arrays.asList(s1); //Array back to Collection for(String s2: sun2){ String s3 = s2; System.out.print(s3); } //sun2.add(new String("Hello")); // throws UnsupportedOperationException } } How can I find the maximum element contained within a Collection? Finding the maximum element within a Collection is easy. The following method can be used which can be found within the Collections class. public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) This method returns the maximum element of the given Collection according to the natural ordering of it's elements. This means that all elements must implement the Comparable interface. With the following code below the implementation of the Comparable interface is already taken care of since the class Byte already implements this interface. import import import import java.util.Set; java.util.ArrayList; java.util.Collection; java.util.Collections;

public class Max{ public static void main(String[] args){ Collection<Byte> numl = new ArrayList<Byte>(); numl.add(new Byte("2")); numl.add(new Byte("6")); numl.add(new Byte("3")); numl.add(new Byte("1")); numl.add(new Byte("5")); numl.add(new Byte("4")); System.out.print("Max element is " + getMax(numl)); } public static Byte getMax(Collection<Byte> c){ return Collections.max(c); } } If the element type being store within the Collection is user defined, implementation of the Comparable interface must be provided. class Num implements Comparable<Num>{ private String i; public Num(String i){

22

this.i = i; } public int compareTo(Num num){ int x = i.compareTo(num.i); return x; } public String getNum(){ return i; } } What is the easiest way to obtain a Map Entry? The easiest way to obtain a Map Entry or (key-value pair) is by invoking the following method provided by the Map interface. Set<Map.Entry<K,V>> entrySet(); The entrySet() method returns a Set which is populated with Map.Entry objects. The only way to obtain a reference to a Map.Entry is by using an Iterator on the returned Set view. Once a reference to a Map.Entry is obtained the follow methods can be invoked which return the key and value corresponding to the entry. K getKey() V getValue() import import import import java.util.Map; java.util.Set; java.util.TreeMap; java.util.Iterator;

public class Emps{ public static void main(String[] args){ Map<String,String> empmap = new TreeMap<String,String>(); empmap.put("956544","Bob Jones"); empmap.put("132485","Phil Harris"); empmap.put("102161","Kamal Uganda"); empmap.put("226545","Bill Russel"); empmap.put("116423","Dorris Smith"); Set s = empmap.entrySet(); for(Iterator i = s.iterator();i.hasNext();){ Map.Entry me = (Map.Entry)i.next(); System.out.println(me.getKey() + " : " + me.getValue()); } } } Is there a way determine how many times an Object occurs within a Collection? The Collections class provides a method which returns the number of times an Object appears within a given Collection. public static int frequency(Collection<?> c, Object o) import java.util.*;

23

public class Freq { public static void main(String[] args){ List<Integer> password = new ArrayList<Integer>(); password.add(new password.add(new password.add(new password.add(new password.add(new Integer(4)); Integer(6)); Integer(8)); Integer(4)); Integer(9));

Integer passwordelement = new Integer(4); System.out.println(passwordelement + " appears " + getFrequency(password,passwordelement) + " times within password"); } private static int getFrequency(Collection c, Object o){ return(Collections.frequency(c,o)); } } How can I create a read only Collection? Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException. Collection<T> unmodifiableCollection(Collection<? extends T> c) List<T> unmodifiableList(List<? extends T> list) Set<T> unmodifiableSet(Set<? extends T> s) SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) import java.util.*; public class Unmod{ public static void main(String[] args){ List<String> strlist = new ArrayList<String>(); strlist.add("C"); strlist.add("B"); strlist.add("A"); Collection<String> unmodstrlist = Unmod.makeUnmodifiable(strlist); // unmodstrlist.add("G"); throws UnsupportedOperationException Set<String> strset = new TreeSet<String>(); strset.add("C"); strset.add("B"); strset.add("A"); Collection<String> unmodstrset = Unmod.makeUnmodifiable(strset); // unmodstrset.add("G"); throws UnsupportedOperationException } public static Collection<String> makeUnmodifiable(Collection<String> c){ return(Collections.unmodifiableCollection(c)); } }

24

How can I get a sorted list of keys that are contained within a Map? The Map interface defines a method named keySet() which concrete classes such as HashMap and TreeMap implement. Depending on the implementation on which keySet() is invoked the returned Set might not contain it's elements (keys) in sorted order. For instance the HashMap class makes no guarantees as to the order of the elements contained within. Whereas the TreeMap class does guarantee element ordering since it implements the SortedMap interface. /* TreeMap used. Keys stored in ascending order */ Map<String,String> book = new TreeMap<String,String>(); book.put(new String("Java"),new String("A trademark used for a programming language designed to develop applications, especially ones for the Internet, that can operate on different platforms.")); book.put(new String("C#"),new String("An object-oriented language devised and promoted by Microsoft, intended to replace Java, which it strongly resembles.")); book.put(new String("Python"),new String("A simple, high-level interpreted language by Guido van Rossum")); book.put(new String("LISP"),new String("A programming language designed to process data consisting of lists. It is widely used in artificial intelligence research.")); Set words = book.keySet(); for(Iterator i = words.iterator();i.hasNext();){ System.out.print(i.next() + "\t"); } How can I traverse a List backwards? In order to traverse a List backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator. ListIterator<E> listIterator() Using a returned ListIterator, concrete implementations of List can be traverse backwards using the following methods. boolean hasPrevious() , previous(),Since ListIterator extends the Iterator interface forward direction is still possible via Iterators methods. boolean hasNext(), E next() import java.util.List; import java.util.ArrayList; import java.util.ListIterator; public class { public static void main(String[] args){ List<String> slist = new ArrayList<String>(); slist.add("1"); slist.add("2"); slist.add("3"); slist.add("4");

25

ListIterator i = slist.listIterator(); while(i.hasNext()){ System.out.print(i.next()); } System.out.println(); while(i.hasPrevious()){ System.out.print(i.previous()); } } } How can i tell if two Collections contain the same elements or have no elements in common? Two methods are needed in this case. boolean containsAll(Collection<?> c) boolean disjoint(Collection<?>c1 Collection<?>c2) Since containsAll(Collection<?> c) is defined within the Collection interface all concrete implementations will be able to use this method. disjoint(Collection<?>c1 Collection<?>c2) is defined within the Collections class. Using both of these methods is pretty straightforward. containsAll(Collection<?> c) is an instance method so naturally it must be invoked on an object. disjoint(Collection<? >c1 Collection<?>c2) is defined as Static within the Collections class so all that is needed is to invoke it using the class name ie Collections.disjoint(Collection<?>c1 Collection<?>c2) How can I shuffle the elements of a Collection? The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection. static void shuffle(List<?> list) static void shuffle(List<?> list, Random rnd) The first method shuffles the elements according to a default source of randomness, with the second using a specified source of randomness. import java.util.*; public class ShuffleTest{ public static void main(String[] args){ List<String> sl = new ArrayList<String>(); sl.add("One"); sl.add("Two"); sl.add("Three"); sl.add("Four"); sl.add("Five"); sl.add("Six"); for(String s: sl){ System.out.println(s); } System.out.println(); Collections.shuffle(sl);

26

for(String s: sl){ System.out.println(s); } } } How can I insert an element into a List? In order to insert an element into a List add(int index, E element) must be used since the List interface does not provide an insert method. If the index is out of rage ie. index < 0 || index > size() an exception will be thrown. import java.util.*; public class Insert{ public static void main(String[] args){ List<String> slist = new ArrayList<String>(); slist.add(new String("Java")); slist.add(new String("Write")); slist.add(new String("run")); slist.add(new String("anywhere!")); slist.add(2,new String("once")); for(String s:slist){ System.out.println(s); } } } How do I traverse a sorted set backwards? Just keep getting the last element and the head set before it: if (!set.isEmpty()) { Object last = set.last(); boolean first = true; do { if (!first) { System.out.print(", "); } System.out.print(last); last=set.headSet(last).last(); first=false; } while (last != set.first()); System.out.println(); } How can I retrieve the items in my HashSet / HashMap in the order they were added? Prior to Java 1.4, you had to manage a separate insertion order list yourself. Starting with Java 1.4, you can use the new LinkedHashMap / LinkedHashSet classes. The iterators you get back from them return the items in insertion order. LinkedHashMap is essentially similar to the LinkedHashSet, its just that you need a key/value pair for each element. Example : String Englishmonths[] = new DateFormatSymbols().getMonths(); String frenchMonths[] = new DateFormatSymbols(Locale.ITALIAN).getMonths(); Map orderedMap = new LinkedHashMap();

27

for (int i = 0, n = months.length; i & lt; n; i++) { orderedMap.put(months[i], italianMonths[i]); } Check to see that iterators for this are aware of the insertion order. So you can walk through the values of the insertion order. Collection values = orderedMap.values(); for (Iterator i = values.iterator(); i.hasNext(); { System.out.println(i.next())); } How an Hashtable can change the iterator? Can a HashMap change the iterator? Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized. The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Hashtable will change the iterator by using Enumerator interface. Yes,we can iterate a hashmap using the entrySet() method. //strings is an ArrayList for (int i=0; i<strings.size(); ++i) { String s = (String) strings.get(i); //do something with s } to for (String s : strings) { //do something with s } there's also the cooler use of it to iterate over the contents of a HashMap, so instead of doing HashMap m = new HashMap(); //... //fill the map with String, Vector values //... Iterator it = m.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next();

28

String value = (Vector) m.get(key); } you can do HashMap m = new HashMap(); //... //fill the map with String, Vector values //... for (String key : m.keySet()) { Vector value = m.get(key); } how hashtable is synchronized?why hashmap is not synchronized?Can we make hashmap synchronized? hashmap is not synchorinized but it part of collections and it enter null values. Hashtable and HashMap both are Key Value pairs and they function both the same way except in sychronization and HashMap accepts one null Key and many null values. HashMap can be synchronized by Map m = collections.synchronizeMap(hashMap); JVM is platform independent/dependent?why?2) which one is faster in execution Array List or Array? why? Array is faster than ArrayList. Because ArrayList can take different type of objects as parameter. by Array is only one type of datatype. ArrayList may faster if u use generics. What is the difference between array and ArrayList ?
Array is collection of same data type. Array size is fixed, It cannot be expanded. But ArrayList is a growable collection of objects. ArrayList is a part of Collections Framework and can work with only objects.

How do I retrieve the values of a Hashtable/HashMap in sorted order? Basically, you can't directly do this. What you can do is get the Collection of values() back from the map and create a sorted collection, or maintain two maps, one in each direction, and keep the second map sorted by being a TreeMap. Which you use depends on the frequency you must sort the elements. import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; public class SortedHashtable { protected Hashtable hashSortedHashtable = new Hashtable(); protected Vector vectSortedHashtable = new Vector(); public Enumeration keys() { return vectSortedHashtable.elements(); }

29

public void clear() { hashSortedHashtable = new Hashtable(); vectSortedHashtable = new Vector(); } public synchronized void put(String key, Entity value) { boolean bSorted = false; for (int i = 0; i < vectSortedHashtable.size(); i++) { Entity base = (Entity) hashSortedHashtable.get(vectSortedHashtable.elementAt(i)); if (base.compareTo(value) > 0) { vectSortedHashtable.insertElementAt(key, i); bSorted = true; break; } } if (!bSorted) { bSorted = true; vectSortedHashtable.addElement(key); } hashSortedHashtable.put(key, value); } protected synchronized void internalPut(String key, Entity value) { vectSortedHashtable.addElement(key); hashSortedHashtable.put(key, value); } public Entity get(String key) { return (Entity) hashSortedHashtable.get(key); } public synchronized void remove(String key) { vectSortedHashtable.remove(key); hashSortedHashtable.remove(key); }

30

} // end SortedHashtable

If you want to maintain a sorted hashtable - either by key or object (item) then you should really extend hashtable and re-implement only the methods that you need to. Call the super methods where you need to. This way it will work with existing code that expects a hashtable. As follows... import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import java.lang.StringBuffer; public class SortedKeyHashtable extends Hashtable { private Vector keyVector = new Vector(); public Enumeration keys () { return keyVector.elements(); }//keys public void clear () { super.clear(); keyVector = new Vector(); }//clear public void put (String key, Vector value) { boolean bSorted = false; for (int i = 0; i < keyVector.size(); i++) { if ((Integer.parseInt(key)) > (Integer.parseInt( (String)keyVector.elementAt(i)))) { keyVector.insertElementAt(key, i); bSorted = true; break; }//i }//f if (!bSorted) { bSorted = true; keyVector.addElement(key); }//i super.put(key,value); }//put public String toString () { StringBuffer strBuf = new StringBuffer(); String key = ""; for (int i = 0; i < keyVector.size(); i++) {

31

key = (String)keyVector.elementAt(i); System.out.println(key); strBuf.append("\n"+key+": "+super.get(key)); }//f return strBuf.toString(); }//toString }//SortedKeyHashtable

How can I add a Collection to another Collection? The java.util.Collection interface includes an addAll(Collection c) method to add one collection to another. How do I traverse a map backwards? Just keep getting the last key and the head map before it: if (!map.isEmpty()) { Object last = map.lastKey(); boolean first = true; do { if (!first) { System.out.print(", "); } System.out.print(last); last=map.headMap(last).lastKey(); first=false; } while (last != map.firstKey()); System.out.println(); } How should I implement object comparisons in a flexible manner? For example, I have a Person class and sometimes I will compare based on name and sometimes I will compare based on age Instead of having the Person class implement the Comparable interface, you could delegate the comparing to another class. Perhaps you could have a PersonComparator interface that you could implement for the various types of comparisons. For example: public interface Person { public String getName(); public int getAge(); } public interface PersonComparator { public int compare(Person p1, Person p2); } public class AgeComparator implements PersonComparator { public int compare(Person p1, Person p2) { if (p1.getAge() == p2.getAge()) return 0; return p1.getAge() > p2.getAge() ? 1 : -1; } }

32

public class NameComparator implements PersonComparator { public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } } How do I count the frequency of some word/object? The Map interface can be used to count the number of times a word/object appears. The following program demonstrates counting word frequency from the command line: import java.util.*; public class MapExample { public static void main(String args[]) { Map map = new HashMap(); Integer ONE = new Integer(1); for (int i=0, n=args.length; i<n; i++) { String key = args[i]; Integer frequency = (Integer)map.get(key); if (frequency == null) { frequency = ONE; } else { int value = frequency.intValue(); frequency = new Integer(value + 1); } map.put(key, frequency); } System.out.println(map); Map sortedMap = new TreeMap(map); System.out.println(sortedMap); } } How do I read input from a stream "one word at a time"? import java.io.*; import java.util.*; public class Test { static final Integer ONE = new Integer(1); public static void main (String args[]) throws IOException { Map map = new TreeMap(); FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { processLine(line, map); } printMap(map); } static void processLine(String line, Map map) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { addWord(map, st.nextToken()); } } static void addWord(Map map, String word) {

33

Object obj = map.get(word); if (obj == null) { map.put(word, ONE); } else { int i = ((Integer)obj).intValue() + 1; map.put(word, new Integer(i)); } } static void printMap(Map map) { Set set = map.entrySet(); Iterator it = set.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); System.out.println(entry.getKey() + ": " + entry.getValue()); } } } Vectors and Threads The thread methods are synchronized so you will not corrupt a vector by manipulating it with more than one thread.However, care must still be taken. Consider the following application: import java.util.*; import java.io.*; class vector3 { public static void ShowVector(Vector v) { String str; for (int i=0; i < v.size();i++) { try { Thread.sleep(100); } catch (InterruptedException e) {} str = (String)v.elementAt(i); System.out.println(i+" :"+str); } public static void main(String args[]) { Vector v; BusyThread T; v = new Vector(); T = new BusyThread(v,1000); T.start(); for (int i=0; i < 10; i++) { System.out.println("Vector had size "+v.size()); ShowVector(v); System.out.println("Vector has size "+v.size()); try { Thread.sleep(1000); } catch (InterruptedException e) {} }

34

} } BusyThread just adds to and removes elements from a vector at random: import java.util.*; class BusyThread extends Thread { Vector v; int count; public BusyThread(Vector v, int count) { this.v = v; this.count = count; } public void run() { double ran; for (int i=0; i < count; i++) { ran = Math.random(); if (ran > 0.5) v.addElement("abcdef"+i); else if (v.size() > 0) v.removeElementAt(0); try { sleep(10); } catch (InterruptedException e) {} } } } The timing is set up to make it likely that the vector will change between when the index is checked against the size of the vector and when the element is gotten from the vector. What is the difference between set and list?- Set stores elements in an
unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements

Q. Can two different keys map to the same object elements? If yes, can you give an example? The answer is YES. In the real world, that is easy. You may have a nickname and an official name or even a fake name, they can be two/three keys in the map, and actually are all mapped to the same physical person: YOU. See the following code example: import java.util.*; public class TestMap { public static void main(String[] args) { HashMap hm = new HashMap(); String sPerson = "The physical person"; hm.put("Official name", sPerson); hm.put("Nick name", sPerson); hm.put("Fake name", sPerson); System.out.println(hm);

35

} } //output //{Official name=The physical person, Fake name=The physical person, Nick name=The physical person}

36

Вам также может понравиться