Just some code snippets that I found useful. Not necessarily the best or fastest solutions.
Generics
Return Types
To get the compiler to understand a generic return type, simply add a dummy class parameter.
public static <A> A someMethod(Class<A> dummy) {
}
// calling the method
someMethod(Double.class);
Collections
Single Element List
Create a list of one single element.
Arrays.asList(element);
Iterable Iterator
Looping over an iteartor with a foreach is not possible. An Iterable is needed.
/**
* Put this method in a Utility class. It can then be imported as class
* or statically.
*/
public static <T> Iterable<T> toIterable(final Iterator<T> the_iterator) {
return new Iterable<T>() {
public Iterator<T> iterator() {
return the_iterator;
}
};
}
...
for(T t : toIterable(an_iterator)) {
// do something
}
Foreach on XML NodeList elements
Creating simple Iterable will allow us to iterate over NodeLists
Iterable<Element> toIterable(final NodeList list) {
return new Iterable<Element>() {
@Override public Iterator<Element> iterator() {
return new Iterator<Element>() {
int position = 0;
@Override public void remove() {
throw new UnsupportedOperationException();
}
@Override public Element next() {
if (!hasNext()) throw new NoSuchElementException();
return (Element) list.item(position++);
}
@Override public boolean hasNext() {
// move to next
while(position < list.getLength() && !(list.item(position) instanceof Element)) ++position;
return position < list.getLength();
}
};
}
};
}
// used
Element someElement = ...;
for (Element child : toIterable(someElement.getChildNodes()) {
/// TODO something
}
Loops
Multiple nested loops break
// given a matrix of size n x k
// we want to know if it contains a value greater than val
double val = 1;
boolean found = false;
label: for(int i = 0; i < n; ++i) {
for(int j = 0; j < k; ++j) {
if (matrix[i][j] > val) {
found = true;
break label; // get out of both for loops
}
}
}
Note: this post might grow in time
No comments:
Post a Comment