A method to return the longest String in a given array of Strings

By Alvin J. Alexander, devdaily.com

Here is the source code for a simple Java method that I use to determine the longest String in an array of Strings.

  /**
   * Return the longest String in a given array. This was initially created to
   * help set the prototype value for a JList.
   * @param array String[] The String array that is passed in.
   * @return String The longest String that is found in the array.
   * @author Alvin J. Alexander, DevDaily.com
   */
  public String getLongestNameInArray(String[] array) {
    int maxWidth = 0;
    String longestString = null;
    for (int i=0; imaxWidth) {
        maxWidth = tmpWidth;
        longestString = array[i];
      }
    }
    return longestString;
  }

I created this for use with setting the prototype value for a JList, i.e., using the setPrototypeCellValue method.


devdaily logo