日期:2014-05-20  浏览次数:20772 次

如何动态创建数组
String str[]={"asd","1sdf","sfe","asd","ddd","sss","ddd","sss","wer","erw"};也就是如何将这个数组中的不同值取出来并保存。这个str的长度并不确定。每取出一个值先判断是否相同,相同的放在一起,不同的有多少个则创建多少个数组保存。

------解决方案--------------------
总觉得这需求好怪。。。。
打印结果:
[1sdf]
[asd, asd]
[ddd, ddd]
[erw]
[sfe]
[sss, sss]
[wer]

Java code

    public static void main(String[] args) {

        String str[] = { "asd", "1sdf", "sfe", "asd", "ddd", "sss", "ddd", "sss", "wer", "erw" };
        Set<String> set = new HashSet<String>();
        Map<String, Integer> map = new TreeMap<String, Integer>();

        for (String s : str) {
            if (set.add(s)) {
                map.put(s, 1);
            } else {
                map.put(s, map.get(s) + 1);
            }
        }

        int size = map.size();
        int i = 0;
        String[][] result = new String[size][];

        for (String key : map.keySet()) {
            if (map.get(key) == 1) {
                result[i] = new String[] { key };
            } else {
                result[i] = new String[map.get(key)];
                for (int j = 0; j < map.get(key); j++) {
                    result[i][j] = key;
                }
            }
            i++;
        }

        for (String[] s : result) {
            System.out.println(Arrays.toString(s));
        }
    }