java 判定一个数组是否是一维数组

如题所述

一维数组的定义
//定义包含三个元素的一维数组
int[] a = new int[3]; a = {1,2,3};//方法1,先new对象,然后赋值
int[] b = {1,2,3}; //方法2,直接赋值
int[] c = new int[]{1,2,3}; //方法3,new后直接赋值,注意不能制定长度
javascript中: String s = new Array("a","b"); 或者 String s = ["a","b"]; 或者 String s = new Array(); s.push("a");s.push("b");
注意:如果用new定义数组时,必须指定其维度,这样定义是错误的: int[] d = new int[];
如果无法确定其元素个数,可以这样定义:int[] e = {};
这样也是错误的: int[] c = new int[3]{1,2,3}; 因为初始化时候已经赋值为0;只能为
int[] c = new int[]{1,2,3};追问

我想要知道一个数组是否是一维数组,例如我定义一个数组 int[] a = new int[]{1,2,3,4};我要怎么判断他是否是一维数组呢?

追答

直接看就看出来了啊
一维数组a[ ]
二维数组a[ ][ ]

三维数组a[ ][ ][ ]

多维数组a[ ][ ][ ]......

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-03
int a[] = {2,3,4};
Object o = a;
if (o.getClass().isArray())
{
String sr = o.getClass().getCanonicalName();
System.out.println(sr);
int idx = sr.indexOf("[]");
if (idx != sr.length() - "[]".length())
{
System.out.println("不是一维数组");
}
else {
System.out.println("是一维数组");
}
}
else {
System.out.println("不是数组");
}
第2个回答  2013-04-03
public class Test {
public static void main(String[] args){
int[] a = new int[] { 1, 2, 3, 4 };
int[][] b = new int[][] { { 1, 2, 3, 4 }, { 1, 2, 3, 4 } };
int[][][] c = new int[][][] { { { 1, 2, 3, 4 }, { 1, 2, 3, 4 } },
{ { 1, 2, 3, 4 }, { 1, 2, 3, 4 } } };
judgeArray(a);
judgeArray(b);
judgeArray(c);
judgeArray(new String());
}
public static void judgeArray(Object obj){
String className=obj.getClass().getCanonicalName();
int i=0;
if (className.length()>2 && className.indexOf("[]")>0) {
while(className.length()>2){
if("[]".equals(className.substring(className.length()-2))){
className=className.substring(0, className.length()-2);
i++;
}else{
break;
}
}
System.out.println(i+"纬数组");
}else{
System.out.println("不是数组");
}
}
}本回答被提问者采纳
第3个回答  2013-04-03
还真没处理过这种问题,有个笨办法,循环数组中的元素,判断当前元素是不是基本类型或者string类型等,如果还可以继续迭代循环就是二维罗,不知可行否?
第4个回答  2013-04-03
这个有意思,暂时不知道答案。