1

如何将 a 转换Set<Set<String>>为 a String[][]?我已经尝试过.toArray(new String[0]),但这似乎并没有奏效。

谢谢!基督教

4

3 回答 3

4

For each Set<String> s in the outer set, convert s to String[] and add it to your Array of arrays.

I don't know any built in way to create n-dimensional arrays from nested collections.

于 2012-12-16T21:51:32.293 回答
1

Loop through the set and create the array

于 2012-12-16T21:51:48.447 回答
0

试试下面的代码,它可以工作

package com.rais;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Rais.Alam
 * @date Dec 17, 2012
 */
public class SetClient
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {

        Set<Set<String>> myArray = new HashSet<Set<String>>();

        Set<String> arr1 = new HashSet<String>();
        Set<String> arr2 = new HashSet<String>();
        Set<String> arr3 = new HashSet<String>();

        arr1.add("a-1");
        arr1.add("a-2");
        arr1.add("a-3");

        arr2.add("b-1");
        arr2.add("b-2");
        arr2.add("b-3");

        arr3.add("c-1");
        arr3.add("c-2");
        arr3.add("c-3");
        arr3.add("c-4");
        arr3.add("c-5");

        myArray.add(arr1);
        myArray.add(arr2);
        myArray.add(arr3);

        String[][] outputArray = convertSetOfSetToArray(myArray);

        for (String[] outerArr : outputArray)
        {
            for (String value : outerArr)
            {
                if (value != null)
                {
                    System.out.println(value);
                }
            }
        }

    }

    public static String[][] convertSetOfSetToArray(Set<Set<String>> myArray)
    {
        int secondArraySize = 0;

        /*
         * Looping array to get the size.
         */
        for (Set<String> innerSet : myArray)
        {
            if (innerSet.size() > secondArraySize)
            {
                secondArraySize = innerSet.size();
            }
        }
        // Declaring and initializing String arrays;
        String[][] outputArray = new String[myArray.size()][secondArraySize];

        int firstIndex = 0;
        int secondIndex = 0;

        for (Set<String> innerSet : myArray)
        {
            for (String value : innerSet)
            {
                outputArray[firstIndex][secondIndex] = value;
                secondIndex++;
            }
            secondIndex = 0;
            firstIndex++;
        }

        return outputArray;
    }

}
于 2012-12-17T05:01:40.130 回答