Sunday, November 30, 2014

Arrays and Indexers in Java



Today's post is about Arrays and Indexers in Java. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Java, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my (not so) recent post (anymore), "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and C++ just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


package javaarrays;
import java.util.Random;

public class JavaArrays {
    
    public static void main(String[] args) {
        
        // Single-dimensional Array(s)  
        printTitle("Reverse Array Elements");  
  
        // Declare and Initialize Array of Chars  
        char[] letters = new char[5];  
        letters[0] = 'A';  
        letters[1] = 'E';  
        letters[2] = 'I';  
        letters[3] = 'O';  
        letters[4] = 'U';  
        
        printArrayChar(letters);  
        char[] inverse_letters = reverseChar(letters);  
        printArrayChar(inverse_letters);  

        printTitle("Sort Integer Array Elements");  

        // Declare and Initialize Array of Integers   
        int[] numbers = { 10, 8, 3, 1, 5 };  
        printArrayInt(numbers);  
        int[] ordered_numbers = bubbleSortInt(numbers);  
        printArrayInt(ordered_numbers);  

        printTitle("Sort String Array Elements");  

        // Declare and Initialize and Array of Strings  
        String[] names = new String[] {                       
                "Damian",   
                "Rogelio",  
                "Carlos",   
                "Luis",                       
                "Daniel"  
            };  
        printArrayString(names);
        String[] ordered_names = bubbleSortString(names);  
        printArrayString(ordered_names);  

        // Multi-dimensional Array (Matrix row,column)  

        printTitle("Transpose Matrix");  

        /* Matrix row=2,col=3 
         * A =  [6  4 24] 
         *      [1 -9  8] 
        */  
        int[][] matrix = { { 6, 4, 24 },   
                           { 1, -9, 8 } };  
        printMatrix(matrix);  
        int[][] transposed_matrix = transposeMatrix(matrix);  
        printMatrix(transposed_matrix);  

        // Jagged Array (Array-of-Arrays)  

        printTitle("Upper Case Random Array & Graph Number of Elements");  
        
        /*              
         * Creating an array of string arrays using the String.Split method 
         * instead of initializing it manually as follows: 
         *  
         * String[][] text = new String[][] {  
         *      new String[] { "word1", "word2", "wordN" },  
         *      new String[] { "word1", "word2", "wordM" },  
         *      ... 
         *      }; 
         *  
         * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
         *  
         */  
        String[][] text = {   
        "Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(" "),  
        "los obstáculos más grandes, nuestras propias indecisiones;".split(" "),  
        "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(" "),  
        "la cosa más fácil, equivocarnos;".split(" "),  
        "la más destructiva, la mentira y el egoísmo;".split(" "),  
        "la peor derrota, el desaliento;".split(" "),  
        "los defectos más peligrosos, la soberbia y el rencor;".split(" "),  
        "las sensaciones más gratas, la buena conciencia...".split(" ")   
        };  
        printJaggedArray(text);  
        upperCaseRandomArray(text);  
        printJaggedArray(text);  
        graphJaggedArray(text);  

        // Array Exceptions  

        printTitle("Common Array Exceptions");  

        printCommonArrayExceptions(null);  
        printCommonArrayExceptions(text);  

        // Accessing Class Array Elements through Indexer  

        printTitle("Alphabets");  

        Alphabet vowels = new Alphabet(5);  
        vowels.set(0, 'a');  
        vowels.set(1, 'e');  
        vowels.set(2, 'i');  
        vowels.set(3, 'o');  
        vowels.set(4, 'u');  
        
        System.out.format("\nVowels = {%s}\n",  
                String.join(",", String.valueOf(vowels.get(0)), 
                    String.valueOf(vowels.get(1)), String.valueOf(vowels.get(2)), 
                    String.valueOf(vowels.get(3)), String.valueOf(vowels.get(4))));
        
        Alphabet en = new Alphabet("abcdefghijklmnopqrstuvwxyz");  
        System.out.format("English Alphabet = {%s}\n", en.toString()); 
        
        System.out.format("Alphabet Extract en[9..19] = {%s}\n",   
                          new Alphabet(en.slice(9, 10))); 
        
        String word1 = String.join("", String.valueOf(en.get(6)), 
                String.valueOf(en.get(14)), String.valueOf(en.get(14)), 
                String.valueOf(en.get(3)));  
        String word2 = String.join("", String.valueOf(en.get(1)), 
                String.valueOf(en.get(24)), String.valueOf(en.get(4)));  
        String word3 = String.join("", String.valueOf(en.get(4)), 
                String.valueOf(en.get(21)), String.valueOf(en.get(4)), 
                String.valueOf(en.get(17)), String.valueOf(en.get(24)), 
                String.valueOf(en.get(14)), String.valueOf(en.get(13)), 
                String.valueOf(en.get(4)));  
  
        System.out.format("\n%s %s, %s!\n", word1, word2, word3);
    }
    
    private static char[] reverseChar(char[] arr) {  
        char[] reversed = new char[arr.length];  
        for (int i = 0, j = arr.length - 1; j >= 0; i++, j--) {
            reversed[i] = arr[j];  
        }
        return reversed;  
    }  
    
    static int[] bubbleSortInt(int[] arr) {  
        int swap;  
        for (int i = arr.length - 1; i > 0; i--) {  
            for (int j = 0; j < i; j++) {  
                if (arr[j] > arr[j + 1]) {  
                    swap = arr[j];  
                    arr[j] = arr[j + 1];  
                    arr[j + 1] = swap;  
                }  
            }  
        }  
        return arr;  
    }  

    static String[] bubbleSortString(String[] arr) {  
        String swap;  
        for (int i = arr.length - 1; i > 0; i--) {  
            for (int j = 0; j < i; j++) {                  
                if (arr[j].charAt(0) > arr[j + 1].charAt(0)) {  
                    swap = arr[j];  
                    arr[j] = arr[j + 1];  
                    arr[j + 1] = swap;  
                }  
            }  
        }  
        return arr;  
    }  
    
    private static int[][] transposeMatrix(int[][] m) {  
        /* Transposing a Matrix 2,3  
         *  
         * A =  [6  4 24]T [ 6  1]  
         *      [1 -9  8]  [ 4 -9] 
         *                 [24  8] 
        */  
        int[][] transposed = new int[m[0].length][m.length];  
        for (int i = 0; i < m.length; i++) {  
            for (int j = 0; j < m[0].length; j++) {  
                transposed[j][i] = m[i][j];  
            }  
        }  
        return transposed;  
    }  

    private static void upperCaseRandomArray(String[][] arr) {  
        Random r = new Random();  
        int i = r.nextInt(arr.length);  
        for (int j = 0; j <= arr[i].length - 1; j++) {
            arr[i][j] = arr[i][j].toUpperCase();  
        }
    }
    
    private static void printArrayChar(char[] arr) {  
        System.out.println("\nPrint Array Content " 
                + arr.getClass().getName() + "[" + arr.length + "]");

        for (int i = 0; i <= arr.length - 1; i++) {
            System.out.format(" array [%2d] = %2s\n", i, arr[i]);   
        }
    }  
    
    private static void printArrayInt(int[] arr) {  
        System.out.println("\nPrint Array Content " 
                + arr.getClass().getName() + "[" + arr.length + "]");

        for (int i = 0; i <= arr.length - 1; i++) {
            System.out.format(" array [%2d] = %2s\n", i, arr[i]);   
        }
    }
    
    private static void printArrayString(String[] arr) {  
        System.out.println("\nPrint Array Content " 
                + arr.getClass().getName() + "[" + arr.length + "]");

        for (int i = 0; i <= arr.length - 1; i++) {
            System.out.format(" array [%2d] = %2s\n", i, arr[i]);   
        }
    }
    
    private static void printMatrix(int[][] m) {  
        System.out.format("\nPrint Matrix Content %s[%d,%d]\n",  
            m.getClass().getName(),
            m.length,  
            m[0].length);

        for (int i = 0; i <= m.length - 1; i++) { 
            for (int j = 0; j <= m[0].length - 1; j++) {
                System.out.format(" array [%2d,%2d] = %2d\n", i, j, m[i][j]);
            }
        }
    }  
    
    private static void graphJaggedArray(String[][] arr) {  
        /* When using Arrays, we can use foreach instead of for:  
         *  
         * for (int i = 0; i <= arr.length - 1; i++) 
         *   for (int j = 0; j <= arr.length - 1; j++)                 
         *  
        */  
        System.out.println("\nPrint Text Content " 
                + arr.getClass().getName());  
        int lineCount = 1;  
        for(String[] s : arr) {  
            System.out.format("Line%2s|", lineCount);  
            for(String w : s) {  
                System.out.format("%3s", '*');  
            }  
            System.out.format(" (%d)\n", s.length);  
            lineCount++;  
        }  
    }  
    
    private static void printJaggedArray(String[][] arr) {  
        StringBuffer line;  
        System.out.println("\nPrint Jagged Array Content " 
                + arr.getClass().getName());  
        for (int i = 0; i < arr.length; i++)  {  
            line = new StringBuffer();  
            for (int j = 0; j < arr[i].length; j++) {  
                line.append(" ").append(arr[i][j]);  
            }
            if (line.toString().equals(line.toString().toUpperCase())) {
                line.append(" <-- [UPPERCASED]");  
            }
            System.out.println(line);  
        }  
    }  
    
    private static void printCommonArrayExceptions(String[][] arr) {  
        try {  
            arr[100][100] = "hola";  
        }  
        catch (NullPointerException | ArrayIndexOutOfBoundsException ex) {  
            System.out.format("\nException: \n%s\n%s\n", 
                    ex.getClass().getName(), ex.getMessage());  
        }  
    }  
    
    private static void printTitle(String message) {
        System.out.println();  
        System.out.println("======================================================");  
        System.out.println(message);
        System.out.println("======================================================");
    }
    
}

class Alphabet {
    // Array Field
    private char[] letters;

    // Indexer Getter/Setter 
    public char get(int index) {
        return letters[index];
    }
    
    public void set(int index, char value) {
       letters[index] = String.valueOf(value).toUpperCase().charAt(0);
    }

    // Getter
    public int getLength() {  
        return this.letters.length;  
    }  
  
    // Constructors  
    public Alphabet(int size) {  
        this.letters = new char[size];  
    }  

    public Alphabet(String list) {  
        this.letters = list.toUpperCase().toCharArray();
    }  

    public Alphabet(char[] list) {  
        this.letters = list;  
    }  
    
    // Overridden Method  
    @Override public String toString() {  
        return String.join(",", (new String(this.letters)).split(""));  
    }  
    
    // Method  
    public char[] slice(int start, int length) {  
        char[] result = new char[length];  
        for (int i = 0, j = start; i < length; i++, j++) {  
            result[i] = this.letters[j];  
        }  
        return result;
    }  
}


The output:








Voilà, that's it. Next post in the following days.

No comments:

Post a Comment