Sunday, February 16, 2014

Returning a Java Array List

A coding problem was presented which the best solution was to have a Java method return a list of string type of data. I've returned int's, floats, single character strings but not necessarily a list. 

A quick refresher on the ArrayList() to become familiar with how it works to include defining it and adding string data. Once the familiarization was completed, it was quickly coded. Of course this started out in a:

public static void main(String args[]) {
   ...rest of code;
}

Once it was working it was cut/pasted out of the main and into its own method shown below.

   public static ArrayList <String> ArrayFunction1 () {   
      ArrayList<String> myArrayList = new ArrayList<String>();
      Logger("ArrayFunction1: Entry");
    
      myArrayList.add("JAN");
      myArrayList.add("FEB");
      myArrayList.add("MAR");
      myArrayList.add("APR");
      Logger("ArrayFunction1: Second element is: " +  myArrayList.get(1));    
      Logger("ArrayFunction1: Exit");
      return myArrayList;
   }


The method was not called as yet as I wanted to make sure there were no javac compile problems. Eventually, the main() was coded to actually call the ArrayFunction1() method.

ArrayList<String> mainArrayList = ArrayFunction1();
Logger("ArrayListTest:main: Size of mainArrayList: " + mainArrayList.size());
Logger("ArrayListTest:main: Third element is: " +  mainArrayList.get(2));

Wondering about what this Logger() method is? 

   public static void Logger(String inStr){
      System.out.println(inStr);
   }


Suppose everyone has one of these somewhere. Overall it was a good refresher on the ongoing learning of Java. Quite simple and basic material. Very handy and will be used again soon.

No comments:

Post a Comment