Seeing the Light in Java: rebuilding python's 'in'

Picture
Java was my first programming language. With time, however, i came to criticize it.... Despite this, i conceded to do my master thesis in java with my pal since we are two students for the subject.

So, i encountered multiple cases where python's "in" operator (see in the table here) would have been perfect. After generic reimplementation (see below), i still found myself caged in java's verbose syntax.

For example, if i wanted to check whether a value in a list of arguments was false, i still had to do things like:

if (Utils.in_list(null, new Object[]{arg1, arg2, arg3})){
...
Which is still rather verbose.

Wasting my time in the documentation as i like to do, i came to search for "java varargs" and "java import a single function from class". This gave me the following code:

/**
 * some utilities
 * @author bernard paulus
 * public domain
 */
public class Utils {
    /**
     * python's 'in' operator -- first attempt
     * @param elem
     * @param list
     * @return true if elem is in list
     */
    public static <T> boolean in_list(T elem, T[] list) {
        // should be named "in" but results in the same erasure when compiled
        // https://www.ibm.com/developerworks/java/library/j-jtp01255/index.html
        // so this method is named "in_list"
        if (elem == null) {
            for (T e : list) {
                if (e == null) {
                    return true;
                }
            }
        } else {
            for (T e : list) {
                if (elem.equals(e)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * python's 'in' operator
     *
     * <br/><br/>
     * Tip: <code>import static Utils.in;</code>
     * @param elem
     * @param elems
     * @return true if elem in list, false otherwise
     */
    public static <T> boolean in(T elem, T ... elems){
        return in_list(elem, elems);
    }
}

This code allows
if (in(null,arg1, arg2, arg3)){
...
when we import the function like this:
import static Utils.in;
Finally, the code shone clearly in my eyes...


As you see, i'm still far from being a java guru... so if you have any interesting pointer or reflection about this (humm... another interesting subject :D ), feel free to post!

the references:
- java varargs
- java static import
Pascale
5/23/2012 12:51:50 am

Bernou <3 Java was my first (and last) programming language too :D

Reply



Leave a Reply.