which may be used to produce a given amount of money.
For example, 11 cents can be produced with
one 10-cent coin and one 1-cent coin,
two 5-cent coins and one 1-cent coin,
one 5-cent coin and six 1-cent coins,
or eleven 1-cent coins.
So there are four unique ways to produce 11 cents.
Assume that the cents parameter is always positive.
*/
The same problem for coins(1,5,10,25,50) has one of below solutions. The solution should satisfy below equation: 1*a + 5*b + 10*c + 25*d + 50*e == cents
public static void countWaysToProduceGivenAmountOfMoney(int cents) {
for(int a =0;a<=cents;a++){for(int b =0;b<=cents/5;b++){for(int c =0;c<=cents/10;c++){for(int d =0;d<=cents/25;d++){for(int e =0;e<=cents/50;e++){if(1*a +5*b +10*c +25*d +50*e == cents){System.out.println("1 cents :"+a+", 5 cents:"+b+", 10 cents:"+c);}}}}}}}
1. How to reverse a single linked list? Solution:- Try a program to reverse the node references (instead of current to next change it to next to
current) using a temp variable.
2. How to reverse a String? Solution:- publicString reverse(String str){
char[] chars = str.toCharArray();int n = chars.length;for(int i =0; i < n/2; i++){char tmp = chars[i];
chars[i]= chars[n-i-1];
chars[n-i-1]= tmp;}returnnewString(chars);}
3. Find out number of bits needed to represent a positive integer in binary?
Solution:-
Just count how many times you shift right before you're left with just zero:
int value =11;int count =0;while(value >0){
count++;
value = value >>1;}
4. Java program to get the max number in an array?
Solution:
max = 0;
for (int i = 0; i < array.length; i++)
{
if(max < array[i])
{
max = array[i];
}
}
5. If you have access to a function that returns a random integer from one to five, write another function which returns a random integer from one to seven.
Random r1 = new Random();
Random r2= new Random();
int m=0;
while(m<=7){
int k = r1.nextInt(5);
int l = (r2.nextInt(5)/2);
int n = (r2.nextInt(5)/3);
m = l+k+n;
System.out.println(m);
if(m==7){
break;
}
}
6.
What order is a hash table lookup?
--Hashtables are sorted by some hash function, not by their natural sort order, so you'd have to extract all the entries O(N) and sort them O(NlogN)
7. What order is determining if a number is even or odd? 1
8. What order is finding an item in an unsorted list? n square
9. What order is a binary search? log n (because n/2) 10.
Given an array of size n, containing every element from 1 to n+1, except one. Find the missing element.
Solution :- (Sum of all the elements from 1 to n+1) - (Sum of all the elements in the array)
11. Sum of elements from 1 to n is n*(n+1)/2
12. Factorial:-
protected static long fact (int n)
{
if (n <= 1)
return 1;
return n * fact (n - 1);
} // method fact
14. Queue using stack:- 2 Stacks:-
Keep 2 stacks, let's call them inbox and outbox.
Queue:
- Push the new element onto inbox
Dequeue:
- If outbox is empty, refill it by popping each element from inbox and pushing it onto outbox
- Pop and return the top element from outbox
Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.
public class SimulatedQueue<E> {
private java.util.Stack<E> stack = new java.util.Stack<E>();
public void insert(E elem) {
if (!stack.empty()) {
E topElem = stack.pop();
insert(elem);
stack.push(topElem);
}
else
stack.push(elem);
}
public E remove() {
return stack.pop();
}
}
Because n is not specified or implied, the number of statements executed is constant—no
matter what n is—so worstTime(n) is O(1). It follows that for the following method in the
HourlyCompany class, worstTime(n) is also O(1):
protected FullTimeEmployee getNextEmployee (Scanner sc) { String name = sc.next(); int hoursWorked = sc.nextInt(); double payRate = sc.nextDouble(); return new HourlyEmployee (name, hoursWorked, payRate); } // method getNextEmployee
Note that the execution of S may entail the execution of millions of statements. For example:
double sum = 0;
for (int i = 0; i < 10000000; i++)
sum += Math.sqrt (i);
The reason that worstTime(n) is O(1) is that the number of loop iterations is constant and
therefore independent of n. In fact, n does not even appear in the code. In any subsequent
analysis of a method, n will be given explicitly or will be clear from the context, so you
needn’t worry about “What is n?”
Skeleton 2. worstTime(n) is O(log n): while (n > 1) { n = n / 2; S } // while
Let t (n) be the number of times that S is executed during the execution of the while
statement. Then t (n) is equal to the number of times that n can be divided by 2 until
n equals 1. By Example A2.2 in Section A2.5 of Appendix 2, t (n) is the largest integer
≤ log2 n. That is, t (n) = floor(log2 n).1 Since floor(log2 n) ≤ log2 (n) for any positive
integer n, we conclude that t (n) is O(log n) and so worstTime(n) is also O(log n).
The phenomenon of repeatedly splitting a collection in two will re-appear time and again
in the remaining chapters. Be on the lookout for the splitting: it signals that worstTime(n)
will be O(log n). The Splitting Rule In general, if during each loop iteration, n is divided by some constant greater than 1, worstTime(n) will be O(log n) for that loop.
As an example of the Splitting Rule, here—from the Arrays class in the package
java.util—is the most widely known algorithm in computer science: the Binary Search
Algorithm. Don’t get hung up in the details; we will study a binary search algorithm
carefully in Chapter 5. Here, n refers to the size of the array being searched. /** * Searches the specified array of ints for the specified value using the * binary search algorithm. The array must be sorted (as * by the sort method, above) prior to making this call. If it * is not sorted, the results are undefined. If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. * * @param a the array to be searched. * @param key the value to be searched for. * @return index of the search key, if it is contained in the list; * otherwise, (-(insertion point) - 1). The * insertion point is defined as the point at which the * key would be inserted into the array a: the index of the first * element greater than the key, or a.length, if all * elements in the array are less than the specified key. Note * that this guarantees that the return value will be greater than * or equal to 0 if and only if the key is found. * @see #sort(int[ ]) */ public static int binarySearch(int[ ] a, int key) { int low = 0; int high = a.length-1; while (low <= high) { int mid = (low + high) >> 1; // same effect as (low + high) / 2, // but see Programming Exercise 3.5 int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } // while return -(low + 1); // key not found. } // method binarySearch
At the start of each loop iteration, the area searched is from index low through index high,
and the action of the loop reduces the area searched by half. In the worst case, the key is not
in the array, and the loop continues until low > high. In other words, we keep dividing
n by 2 until n = 0. (Incidentally, this repeated dividing by 2 is where the “binary” comes
from in Binary Search Algorithm.) Then, by the Splitting Rule, worstTime(n) is O(log n)
for the loop. And with just a constant number of statements outside of the loop, it is clear
that worstTime(n) is O(log n) for the entire method.
Skeleton 3. worstTime(n) is O(n): for (int i = 0; i < n; i++) { S } // for
The reason that worstTime(n) is O(n) is simply that the for loop is executed n times. It
does not matter how many statements are executed during each iteration of the for loop:
suppose the maximum is k statements, for some positive integer k. Then the total number
of statements executed is ≤ kn. Note that k must be positive because during each iteration,
i is incremented and tested against n.
As we saw in Section 3.1, worstTime(n) is O(n) for the aboveMeanCount method. But
now we can obtain that estimate simply by noting that the loop is executed n times. public static int aboveMeanCount (double[ ] a, double mean) { int n = a.length, count = 0; for (int i = 0; i < n; i++) if (a [i] > mean) count++; return count; } // method aboveMeanCount
For another example of a method whose worstTime(n) is O(n), here is another method
from the Arrays class of the package java.util. This method performs a sequential
search of two arrays for equality; that is, the search starts at index 0 of each array, and
compares the elements at each index until either two unequal elements are found or the
end of the arrays is reached. /** * Returns true if the two specified arrays of longs are * equal to one another. Two arrays are considered equal if both * arrays contain the same number of elements, and all corresponding pairs * of elements in the two arrays are equal. In other words, two arrays * are equal if they contain the same elements in the same order. Also, * two array references are considered equal if both are null. * * @param a one array to be tested for equality. * @param a2 the other array to be tested for equality. * @return true if the two arrays are equal. */ public static boolean equals (long[ ] a, long[ ] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true; } // method equals Skeleton 4. worstTime(n) is O(n log n): int m; for (int i = 0; i < n; i++) { m = n; while (m > 1) { m = m / 2; S } // while } // for
The for loop is executed n times. For each iteration of the for loop, the while loop
is executed floor(log2 n) times—see Example 2 above—which is ≤ log2 n. Therefore
worstTime(n) is O(n log n). We needed to include the variable m because if the inner loop
started with while (n > 1), the outer loop would have terminated after just one iteration.
In Chapter 11, we will encounter several sorting algorithms whose worstTime(n) is
O(n log n), where n is the number of items to be sorted.
Skeleton 5. worstTime(n) is O(n2): a. f.aor (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { S } // for j
The number of times that S is executed is n2. That is all we need to know to conclude
that worstTime(n) is O(n2). In Example 3.3, we painstakingly counted the exact number
of statements executed and came up with the same result. b. f.bor (int i = 0; i < n; i++) for (int k = i; k < n; k++) { S } // for k
The number of times that S is executed is
n + (n − 1) + (n − 2)+· · ·+3 + 2 + 1 =
n
k=1
k
As shown in Example A2.1 of Appendix 2, the above sum is equal to
n(n + 1)/2,
which is O(n2). That is, worstTime(n) is O(n2).
The selectionSort method, developed in Chapter 11, uses the above skeleton. Here,
n refers to the size of the array to be sorted. /** * Sorts a specified array of int values into ascending order. * The worstTime(n) is O(n * n). * * @param x – the array to be sorted. * */ public static void selectionSort (int [ ] x) { // Make x [0 . . . i] sorted and <= x [i + 1] . . .x [x.length -1]: for (int i = 0; i < x.length -1; i++) { int pos = i; for (int j = i + 1; j < x.length; j++) if (x [j] < x [pos]) pos = j; int temp = x [i]; x [i] = x [pos]; x [pos] = temp; } // for i } // method selectionSort
There are n − 1 iterations of the outer loop; when the smallest values are at indexes x
[0], x [1], . . . x [n − 2], the largest value will automatically be at index x [n − 1]. So
the total number of inner-loop iterations is
(n − 1) + (n − 2) + . . . + 1 =
n−1
i=1
i = n(n − 1)/2
We conclude that worstTime(n) is O(n2).
c. f.cor (int i = 0; i < n; i++)
{
S
} // for i
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
S
} // for j
For the first segment, worstTime(n) is O(n), and for the second segment, worstTime(n)
is O(n2), so for both segments together, worstTime(n) is O(n + n2), which is equal to
O(n2). In general, for the sequence
A
B
if worstTime(n) is O(f ) for A and worstTime(n) is O(g) for B, then worstTime(n) is
O(f + g) for the sequence A, B.
1. Batch Fetching. Defined batch-size in hibernate xml for the collection, would fetch the items in a single query. Create the proxies. 2. Subselects. Fetch="subselect" would create a sub query for getting the child elements. 3. Joins. Fetch="Joins" would disable lazy loading and create a single query with joining the child table. If we just define lazy = false or Fetch = eager, it would execute two queries first for parent and second for child. Hibernate executes outer joins. If we write , hibernate would execute inner join.
1.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.
2.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.
3.When I wrap a collection to be read-only or synchronized, why can’t I call any of the collection methods via reflection without getting an IllegalAccessException ?
When you wrap a collection through the static methods of the Collections class, this creates an instance of a package-private (default access) class. Because you don’t have access to these classes, you can’t call their methods via reflection (though you can call their methods directly through the appropriate interface).
4.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).
5.What is the minimum number of key-value pairs for which it makes sense to use a HashMap, as opposed to using a pair of arrays (one for keys, the other for values) with brute-force key searches ?
Many people often need maps for very small numbers (2-5) of key-value pairs. When does it make sense to forgo the convenience of the HashMap to avoid the associated overhead?
Well, is there really that much of a performance loss using a HashMap? There is no synchronization penalty (unless you impose your own). You can tune the sizing by adjusting the initial size and load factor. Plus, do you really want to be responsible for “rolling your own” code to handle the dynamic resizing of the key and value arrays, inserting/removing data from these arrays, optimizing the searching algorithm, etc. Yuck!
In general, the performance hit associated with using a general purpose Map (such as the HashMap) is far outweighed by the benefits of using a simple interface backed by a tested algorithm.
The only reason I could see wanting to use arrays is to guaruntee the type of your key/values to add type checking and avoid casting. Still, if this is a critical aspect of your application, you can wrap your HashMap in another object to provide type-safety, and the casting overhead should be minimal.
Another alternative to creating a custom solution is to explore other collection classes, such as ObjectSpaces’s JGL Libraries. There may be something there that would suit your needs.
So, to answer your question, I would say that the fewer the key-value pairs you have, the more reason you have to use a HashMap. Since the fewer the keys, the faster the search, why not use it for 2-5 key-value pairs. I would think that only when you get to many pairs (tens of thousands) and there is a performance problem you should consider an alternative. Basically, exhaust your search of tried-and-true collections before you try a custom solution. Let other people create these collections so you can focus on your application.
6.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.
7.What is the default initial size for a Hashtable / HashMap ?
This depends on what version of Java you are using. For JDK 1.2, the size was 101. For JDK 1.3, the size changed to 11.
8.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.
9.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.
10.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. You can add it, but it isn’t there by default.
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.
11.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.
ArrayList it’s part of the Java Collection Framework, and has been added with version 1.2, while Vector it’s an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.
The main difference is that Vector it’s a synchronized object, while ArrayList it’s not.
While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the orignal object has been modified), the Enumeration returned by Vector are not.
Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList.
12.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;
}
}
public class NameComparator implements PersonComparator {
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
This is a very simple example of the Strategy Pattern. This allows your comparisons and your object to change independent of one another.
13.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};
// 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));
14.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.
15.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).
16.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);
17.How can I easily shift the elements in a List / Vector such that all the elements rotate n elements ? The Java 1.4 API adds a rotate() method to the Collections class: rotate(List list, int distance) that will shift the elements for you.
18.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)));
This works because the set() method returns the original element.
19.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.
20.How do I convert an old-style Enumeration to something in the Collections Framework ? Prior to Java 1.4, any conversion had to be manually done. With the introduction of 1.4, you can call Collections.list(enumeration) to automatically convert the Enumeration to an ArrayList.
21.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.
22.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.
23.How can I use two iterators to go through a collection ? Just get a separate iterator for each loop:
Collection l = …;
for(Iterator i = l.iterator(); …) {
for(Iterator j = l.iterator();…) {
}
}
24.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();
}
25.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();
}
26.How can I go through an Iterator mulitple times ? There is no direct support for this. You’ll need to create your own caching mechanism. For instance, as you go through the Iterator the first time, add the elements to a LinkedList. Then, you can just get an Iterator from the LinkedList for the second pass through.
27.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)
28.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).
29.Is Vector’s clone method thread-safe ?
Sure it is, since it is a Vector which is thread-safe.
30.How do I load property settings with the Properties class ?
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”);
//Just a trick: in a web archive (war) you can get the InputStream inside the war archive using
ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream(“it/package/application.properties”);
This is better than using a FileInputStream, because you are loading the file within the archive as it was a resource. You should use this.getClass().getClassLoader() to use the same ClassLoader as the one used the servlet container to load your JSP/Servlet. This code is snipped from a JSP page inside Tomcat.
31.How do I save properties settings with the Properties class ?
Try this:
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.
32.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.
For synchronizing a HashMap, you can use Collections.synchronizedMap() which will return a synchronized map for you, which is thread-safe.
Remember, synchronization will cause a performance problem. So, it needs to be used carefully, when really required.
33.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[] 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 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 sun = new ArrayList();
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
for(int i = 0; i < s1.length; ++i){
String contents = s1[i];
System.out.print(contents);
}
System.out.println();
List 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
}
}
34.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 c)
LinkedList(Collection c)
Vector(Collection c)
TreeSet(Collection 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 slist = new ArrayList();
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();
List s2list = new ArrayList(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 slist = new ArrayList();
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 s2set = new TreeSet(slist);
for(String s : s2set){
System.out.print(s + “\t”);
}
35.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{
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{
public static void main(String[] args){
List alpha = new ArrayList();
alpha.add(new Alpha(“z”));
alpha.add(new Alpha(“g”));
alpha.add(new Alpha(“k”));
alpha.add(new Alpha(“q”));
alpha.add(new Alpha(“a”));
alpha.add(new Alpha(“b”));
alpha.add(new Alpha(“o”));
alpha.add(new Alpha(“v”));
alpha.add(new Alpha(“c”));
Collections.sort(alpha);
System.out.println(alpha);
}
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{
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 = 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);
}
public int compareTo(Car car){
int i = brand.compareTo(car.brand);
return(i != 0 ? i : model.compareTo(car.model));
}
}
36.What are Generics and how can I use them ? One of the biggest additions since the creation of the Collections framework is Generics.This long awaited update to the type system is a welcomed feature, which C++ developers have had in their toolbox for years using the STL. 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{
public add(E e);
Iterator iterator();
}
public interface Iterator{
E next();
boolean hasNext();
}
Type Safe Collections
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 s = new SortedSet();
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 l = new ArrayList();
l.add(new String(“Java”));
Integer i = l.get(0);
Generics and Subtyping
Generics do not share some of the things that are commonly held true in the Java language and one of them is subtyping. One would assume the following perfectly legal since it is true that Object is a supertype of String. But the following is in fact illegal and will cause a compile time error.