2

I have a C# method that use "params" modifier for a 2-dimentions array.

/// <summary>
///   Combine vectors horizontally.
/// </summary>
/// 
public static T[] Concatenate<T>(params T[][] vectors)
{
    int size = 0;
    for (int i = 0; i < vectors.Length; i++)
        size += vectors[i].Length;

    T[] r = new T[size];

    int c = 0;
    for (int i = 0; i < vectors.Length; i++)
        for (int j = 0; j < vectors[i].Length; j++)
            r[c++] = vectors[i][j];

    return r;
}

I convert it to Java like this:

{
    int size = 0;
    for (int i = 0; i < vectors.length; i++)
    {
        size += vectors[i].;
    }

    T[] r =(T[]) Array.newInstance(vectors[0][0].getClass(), size);

    int c = 0;
    for (int i = 0; i < vectors.length; i++)
    {
        for (int j = 0; j < vectors[i].length; j++)
        {
                r[c++] = vectors[i][j];
        }
    }

    return r;
}

But it seems to be wrong. Solution doesn't work. Please someone tell me the right way. Thanks a lot.

fatpipp
  • 213
  • 1
  • 4
  • 12
  • 2
    you have a syntax error on line 4 in your java code. Furthermore, its imcomplete, where is the method declaration? What does "doesn't work" mean? What do you expect to happen, what does happen? – Polygnome Jun 10 '12 at 13:09
  • If vectors is of size 0 or vectors[0] if of size 0, your Java code won't work. – Danny Varod Jun 10 '12 at 13:12
  • [Stack Overflow is not a code translation service](http://meta.stackexchange.com/a/129362). Please explain the requirements in plain English, not in code in another programming language. – dtb Jun 10 '12 at 13:29

2 Answers2

2

In Java you use ... instead of params, as is explained here

So you declare your method like this (note the loss of one []):

public static T[] Concatenate<T>(T[]...vectors)
Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171
0

A couple of suggestions:

  • Just avoid using arrays and generics together. Thanks to type earasure, they don't play well together. (You don't have that problem on CLR.)

  • Prefer existing solutions. Guava's Iterables.concat appears to fit the bill here.

missingfaktor
  • 90,905
  • 62
  • 285
  • 365