Skip to content

Instantly share code, notes, and snippets.

@speters33w
Last active September 15, 2023 01:42
Show Gist options
  • Save speters33w/4aa1869775af9dffff03eadbdb0b0d11 to your computer and use it in GitHub Desktop.
Save speters33w/4aa1869775af9dffff03eadbdb0b0d11 to your computer and use it in GitHub Desktop.
Simple example of converting an Arraylist to a String array and String array to an ArrayList and "adding" an element to a String array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArraysSample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(); // Create an ArrayList of Strings
list.add("CSU"); // Add a String to the ArrayList
list.add("Global"); // Add a String to the ArrayList
System.out.printf("%s%n", list.toString()); // Print the ArrayList [CSU, Global]
String[] stringArray = list.toArray(new String[0]); // Convert the ArrayList to an array of Strings
System.out.println(stringArray); // Prints the OBJECT,
// example: [Ljava.lang.String;@378bf509
System.out.println(Arrays.toString(stringArray)); // Prints the array [CSU, Global]
String[][] stringArray2d = {{ "CSU", "Global" }, // Create a 2D array of Strings
{ "CSC", "320" }};
System.out.println(Arrays.toString(stringArray2d)); // Prints the OBJECTS in the 2d Array,
// example: [[Ljava.lang.String;@5fd0d5ae,
// [Ljava.lang.String;@2d98a335]
System.out.println(Arrays.deepToString(stringArray2d)); // Prints the 2D array [[CSU, Global], [CSC, 320]]
stringArray = addElement(stringArray, "CSC"); // Uses the addElement() method
// to add a String to the array.
stringArray = addElement(stringArray, "320"); // adds another String to the array.
System.out.println(Arrays.toString(stringArray)); // Prints the "modified" array [CSU, Global, CSC, 320]
List<String> ArrayList = Arrays.asList(stringArray); // Converts the String array to a List
System.out.printf("%s%n", ArrayList.toString()); // Prints the converted List [CSU, Global, CSC, 320]
}
/**
* Method to "add" an element to an immutable array.
* @param array the array to add the element to.
* @param element the element to add to the array.
* @return an array with the element added to it.
*/
public static String[] addElement(String[] array, String element) {
String[] newArray = new String[array.length + 1]; // Create a new String[] with length +1
System.arraycopy(array, 0, newArray, 0, array.length); // Copy the elements to the new array
newArray[newArray.length - 1] = element; // Add the new element to the new array
return newArray; // Return the modified new array
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment