Dec
20
2007

in_array() and implode() for Java



Comments available as RSS 2.0

I'm still getting to grips with Java, but there a few functions I miss coming from PHP. in_array lacks a Java equivalent, as does the implode function. Here are the equvalent methods in Java:

implode()

public static String implode(String[] ary, String delim) {
    String out = "";
    for(int i=0; i<ary.length; i++) {
        if(i!=0) { out += delim; }
        out += ary[i];
    }
    return out;
}

in_array()

public static boolean in_array(DefaultListModel haystack, String needle) {
    for(int i=0;i<haystack.size();i++) {
        if(haystack.get(i).toString().equals(needle)) {
            return true;
        }
    }
    return false;
}
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Comments

  1. rgfdg says:

    You should use the StringBuilder in your implode method.

  2. Java has built in functionality to search arrays using “Arrays.binarySearch”, but only drawback is that the array needs be sorted before it’s searched.


    public static boolean in_array(Object needle, Object[] haystack) {
    Arrays.sort(haystack);
    return (Arrays.binarySearch(haystack, needle) >= 0);
    }

  3. Echilon says:

    The problem with sorting first is that you need to loop over the array twice. You might not need it sorted.

  4. Echilon says:

    Probably, I was new to Java when I posted this.

  5. milo says:

    super!!!! Really help a lot!!!

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment

Powered by WP Hashcash