traverse Array to String - Android java.lang

Android examples for java.lang:array convert

Description

traverse Array to String

Demo Code

import java.util.Arrays;

public class Main {

  private static void traverseArray(StringBuilder result, Object object) {
    if (!isArray(object)) {
      result.append(object.toString());//  w  w w.j  a  va 2s.c om
      return;
    }
    if (getArrayDimension(object) == 1) {
      switch (getType(object)) {
      case 'I':
        result.append(Arrays.toString((int[]) object)).append("\n");
        return;
      case 'D':
        result.append(Arrays.toString((double[]) object)).append("\n");
        return;
      case 'Z':
        result.append(Arrays.toString((boolean[]) object)).append("\n");
        return;
      case 'B':
        result.append(Arrays.toString((byte[]) object)).append("\n");
        return;
      case 'S':
        result.append(Arrays.toString((short[]) object)).append("\n");
        return;
      case 'J':
        result.append(Arrays.toString((long[]) object)).append("\n");
        return;
      case 'F':
        result.append(Arrays.toString((float[]) object)).append("\n");
        return;
      case 'L':
        result.append(Arrays.toString((Object[]) object)).append("\n");
      default:
        return;
      }
    }
    for (int i = 0; i < ((Object[]) object).length; i++) {
      traverseArray(result, ((Object[]) object)[i]);
    }
  }

  public static String traverseArray(Object object) {
    StringBuilder result = new StringBuilder();
    traverseArray(result, object);
    return result.toString();
  }

  public static int getArrayDimension(Object objects) {
    int dim = 0;
    for (int i = 0; i < objects.toString().length(); ++i) {
      if (objects.toString().charAt(i) == '[') {
        ++dim;
      } else {
        break;
      }
    }
    return dim;
  }

  public static char getType(Object object) {
    if (isArray(object)) {
      String str = object.toString();
      return str.substring(str.lastIndexOf("[") + 1, str.lastIndexOf("[") + 2).charAt(0);
    }
    return 0;
  }

  /**
   * ???????
   */
  public static boolean isArray(Object object) {
    return object.getClass().isArray();
  }

}

Related Tutorials