1

I want to create an array which its length is fixed, but the elements are reference to Iterable objects. Just like creating an array with pointer elements in C, where the pointers can point to lists of any length.

I tried this:

// declaration
private Iterable<String>[] a;
...
// in construtor, n is known length.
a = (Iterable<String>[]) new Object[n];

The compiler gives me a warning. And when I execute the program. the exception below is thrown.

Exception in thread "main" java.lang.ClassCastException: 
[Ljava.lang.Object; cannot be cast to [Ljava.lang.Iterable;

I searched through the web. But the results are all dynamic array but not fixed-length array with dynamic elements. Thanks a lot if you can help!

UPDATE

I'll try to put it simpler. What I want is like an array of references, and the reference can point to some Iterable object.

leowang
  • 341
  • 3
  • 11
  • Did you read what it says? You cannot cast an Object to an Iterable. – hichris123 Nov 28 '13 at 03:06
  • 3
    Why you don't use ArrayList ? It take less effort but more effective. – Tien Nguyen Nov 28 '13 at 03:07
  • if you want to guarantee the size is always constant and still use an iterable, you might first create a normal array and convert it to a list to use iterable over it (e.g Arrays(a).asList) hoping you know what you are doing – bjhaid Nov 28 '13 at 03:11
  • If you want to enforce fixed-length beyond creation time, you can use FixedSizeList from the Commons library. – Nathan Merrill Nov 28 '13 at 03:33
  • @TienNguyen I tried `ArrayList`, in which I declare like this `private ArrayList> a`. But after I initialize it with a initial count 4, and trying to add a queue into index 3, an exception is thrown. – leowang Nov 28 '13 at 03:41
  • @hichris123 Yes, I know it, but Java doesn't allow generic array neither. – leowang Nov 28 '13 at 03:42

3 Answers3

1

I'll assume that you really do want an array whose elements are Iterable<String>, so I won't tell you to use a different data structure. (Though that might be a good idea.)

You're running squarely into a terrible mismatch in Java between arrays and generics.

As you discovered, Object[] is not compatible with Iterable<String>[]. So as a first attempt you could try to create an array of Iterable:

Iterable<String>[] a = new Iterable[n];

This will give you a "rawtypes" warning. You then might try to create a generic array like this:

Iterable<String>[] a = new Iterable<String>[n]; // ERROR

but this gives a compiler error, "generic array creation." See this answer for the reason why. Briefly, the reason is that generics are generally erased and arrays are reified. The only reified generic type is the unbounded wildcard <?>, so you have to create an array of this type and cast it:

Iterable<String>[] a = (Iterable<String>[])new Iterable<?>[n];

Now this gives you an unchecked warning. This is unavoidable, so you have to suppress it:

@SuppressWarnings("unchecked")
Iterable<String>[] a = (Iterable<String>[])new Iterable<?>[n];

So that's what you have to do to create an array of a generic type.

Community
  • 1
  • 1
Stuart Marks
  • 112,017
  • 32
  • 182
  • 245
0
I think you need to use something like this:-

ArrayList<Iterable<String>> temp = new ArrayList<Iterable<String>>();
        Iterable<String> ob1=new Iterable<String>(){

            @Override
            public Iterator<String> iterator() {
                // TODO Auto-generated method stub
                return new ArrayList<String>().iterator();
            }

        };
        temp.add(ob1);
Kishore
  • 190
  • 2
  • 14
  • Yes, I tried this, but when initializing it with count 4, and trying to add a Iterable object like queue into index 3, an exception is thrown. – leowang Nov 28 '13 at 03:49
  • ArrayList grows dynamically, what kind of exception is thrown? – Kishore Nov 28 '13 at 03:57
  • As you say, it just grows dynamically. The exception is `IndexOutOfBounds` with a hint that `Size is 0, index is 3`. It seems that even if I initialize it with 4, I cannot add into index 3 at first, meaning that I cannot access it just like an array. – leowang Nov 28 '13 at 05:00
0

Check the code given below. you dont have to create Object array rather an iterable array

@SuppressWarnings("unchecked")
    public static void main(String[] args) {
        Iterable<String>[] iterableArr;//array definition
        //Java doesn't allow creation of generic type array (e.g. new Iterable<String>[]), 
        //so you can create a raw type array (e.g. new Iterable[2]). It generates compiler warning, which can be supressed.
        iterableArr = new Iterable[2];//array initialization

        List<String> list1 = new ArrayList<String>(); //Creating and adding list1 to iterableArr
        list1.add("1");
        list1.add("2");
        list1.add("3");
        iterableArr[0] = list1;

        List<String> list2 = new ArrayList<String>(); //Creating and adding list2 to iterableArr
        list2.add("A");
        list2.add("B");
        list2.add("C");
        iterableArr[1] = list2;

        //printing the data
        for (Iterable<String> iterable : iterableArr) {
            for (Iterator<String> iterator = iterable.iterator(); iterator.hasNext();) {
                String string = (String) iterator.next();
                System.out.print(string+" ");
            }
            System.out.println("");
        }
    }
Kaushal
  • 595
  • 8
  • 19