Wednesday, February 03, 2010

Dynamic Java String Array

A business needed to split data elements in the display to it's customers via a report. Since the data was returned from the Java Data Access Object layer as a String array, the quickest way was to detect an existing data item and then insert what the business wanted to display in the report for that data item.

Here is an example of what I did to dynamically insert items into a Java String array:

public class DynamicStringArray {
public static void main(String[] args){
String[] originalArray = {"a","b","d"};

System.out.println("----- Original String Array ----");
for(int i = 0; originalArray.length > i; i++){
System.out.println(originalArray[i]);
}

//create a fixed-size ArrayList from the String array.
ArrayList oldList = new ArrayList(Arrays.asList(originalArray));
//create an ArrayList to hold the inserted items.
ArrayList newList = new ArrayList();

//assume no "b" in the array
boolean hasB = false;

//check if the array has a "b"
for(int i = 0; originalArray.length > i; i++){
if(originalArray[i].equalsIgnoreCase("b")){
hasB = true;//we have a "b" Houston
}
}

if(hasB){//the array has a "b"
for(int i = 0; oldList.size() > i; i++){
if(oldList.get(i) == "b"){//found "b"
newList.add(i,"newB");//replace "b" with "NewB"
newList.add(i + 1,"c");//add "c"
}else{//not "b"
newList.add(oldList.get(i));
}
}
}

//create new String array
String[] newArray = new String[newList.size()];
newList.toArray(newArray);
//pass new String array to old String array
originalArray = newArray;

System.out.println("----- Updated String Array -----");
for(int i = 0; originalArray.length > i; i++){
System.out.println(originalArray[i]);
}

}
}

The above code results in the following:

No comments: