Write a static method named shortestString that accepts an A

Write a static method named shortestString that accepts an ArrayList of Strings as a parameter, and returns the shortest string in the Array List (the string with the fewest characters).

If the array list is null, or empty the method should return null. If there are ties for the shortest string then the method can return any of the tied values.

Solution

ShortestArrayListString.java

import java.util.ArrayList;


public class ShortestArrayListString {

  
   public static void main(String[] args) {
           ArrayList<String> list = new ArrayList<String>();
           list.add(\"aaaaaa\");
           list.add(\"bbbbb\");
           list.add(\"cc\");
           list.add(\"ddddd\");
System.out.println(\"Shortest String is: \"+shortestString(list));

   }
   public static String shortestString(ArrayList<String> list){
       if(list == null || list.size() == 0){
           return null;
       }
       else{
           String minString = list.get(0);
           for(String s: list){
               if(minString.length() > s.length()){
                   minString = s;
               }
           }
           return minString;
       }
   }

}

Output:

Shortest String is: cc

Write a static method named shortestString that accepts an ArrayList of Strings as a parameter, and returns the shortest string in the Array List (the string wi

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site