18

I am declaring this class, that doesn't to be useful.

public class ArrayTrick {

    public static char[] arr(char... arr) {
        return arr;
    }

    public static float[] arr(float... arr) {
        return arr;
    }

    public static double[] arr(double... arr) {
        return arr;
    }

    public static long[] arr(long... arr) {
        return arr;
    }

    public static int[] arr(int... arr) {
        return arr;
    }

    public static short[] arr(short... arr) {
        return arr;
    }

    public static byte[] arr(byte... arr) {
        return arr;
    }

    public static boolean[] arr(boolean... arr) {
        return arr;
    }

    public static <T> T[] arr(T... arr) {
        return arr;
    }

}

which allows me (once I have a static import in my code) to declare arrays like this:

int[][] arr = arr(
   arr(1, 2, 1),
   arr(2, 1, 3),
   arr(3, 3, 3));

personally I find it useful and the few people I work with understand it.

It comes from the fact that I got frustrated by java array declaration after working in python, and I sometime work with keyboards where the curly brackets are hard to find (Italian standard on my old laptop).

What I want to know is : Is there anything bad about working like that? Is it readable enough in your opinion? How come this trick is not famous?

3
  • 15
    Be careful not to write your own programming language on top of java that recreates existing functionality; only bad things lie down that road. Commented Aug 14, 2013 at 22:29
  • 1
    just don't use arrays but List and Arrays.asList Commented Aug 15, 2013 at 6:56
  • 5
    are you getting ready for Talk Like a Pirate Day? :)
    – Roald
    Commented Aug 20, 2013 at 19:37

6 Answers 6

45

Not much different from

int[][] arr = {{1, 2, 1},
               {2, 1, 3},
               {3, 3, 3}};

Also, I don't think you can run away from curly brackets in java :)

5
  • 29
    yourMethod(new int[][] {{ 1, 2, 1}, {2, 1, 3}, {3, 3, 3}}); works
    – rocketboy
    Commented Aug 14, 2013 at 15:06
  • 2
    you can't do generic arrays this way. see my answer
    – ZhongYu
    Commented Aug 14, 2013 at 15:38
  • 1
    -1 This is not where the difference comes into play. It comes into play when you have something like foo(new int[]{1,2,3}) vs foo(arr(1,2,3)).
    – arshajii
    Commented Aug 14, 2013 at 16:08
  • 6
    @arshajii There's extreme little size difference there, and the new int form is using plain Java. Using arr is just a trick that's going to cause "Why the hell did he do it this way, and does arr do something special under the hood?" issues for maintainers later on
    – Izkata
    Commented Aug 15, 2013 at 1:33
  • @Izkata Well the size difference can become distinct when you have foo(new SuperLongClassName[]{...}) vs foo(arr(...)). As for the maintainability issue, I think that's definitely possible, but this answer doesn't cover any of that, which is why my -1 still stands.
    – arshajii
    Commented Aug 16, 2013 at 14:21
19

It's readable enough, but it's not famous or used often because it's so much easier to declare and initialize on the same line using:

int[][] arr = {
        {1,2,1},
        {2,1,3},
        {3,3,3}};
0
8

The trick's not famous because you really don't need it with the curly bracket notation. Is it really a help to avoid those curly brackets? In C-related languages, I think there's no avoiding them.

Array initialization:

int[][] arr = {
    {1, 2, 1},
    {2, 1, 3},
    {3, 3, 3}
};

Your version is readable enough, but since I know the language supports this, I'd wonder if the function would do anything more.

1
  • 1
    @jlordo Aww darn, I'm so sorry. Should've paid more attention. Fixed!
    – Janis F
    Commented Aug 14, 2013 at 15:11
4

Is that necessary?, what about:

    String[][] arr = {{"2","3","4"},
                     {"3","4","5"},
                     {"4","5","6"}};
0
1

The only time I used ArrayTrick type declarations is when I would want to use varargs in a situation where varargs cannot be declared in a method call. This is typically where a handler is used.

Example,using an example I deal with everyday, and using my library I have written, SQLExecutor, consider the following:

final String SQL_QUERY = "Select* from transaction where TRANSACTION_ID = ? AND TRANSACTION_TYPE >= ?";
final String DATABASE_CONNECTION_STRING = "";
final String USER_NAME = "";
final String PASSWORD = "";

Connection connection = null;
try {
    connection = DriverManager.getConnection(DATABASE_CONNECTION_STRING, USER_NAME, PASSWORD);
    SQLQueryExecutor executor = new BasicSQLQueryExecutor();
    executor.setConnection(connection); //ALWAYS pass a Connection.
    executor.setCloseConnection(false);

    Transaction transaction = executor.executeQuery(SQL, VarargsUtils.toArray(1294, "EFT"), new IterativeResultSetHandler<BigDecimal[]>() {

        /* (non-Javadoc)
        * @see za.co.sindi.sql.IterativeResultSetHandler#handle(za.co.sindi.sql.ResultSetIterator)
        */
        @Override
        public BigDecimal[] handle(ResultSetIterator iterator) throws SQLException {
        // TODO Auto-generated method stub
            Transaction transaction = new Transaction();
            while (iterator.hasNext()) {
                Map<Object, Object> attributes = iterator.next();
                transaction.setTransactionId(attributes.get("TRANSACTION_ID"));
                transaction.setTransactionType(attributes.get("TRANSACTION_TYPE"));
            }

            return transaction;
        }
    });
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (DatabaseExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    try {
        SQLUtils.close(connection);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

The IterativeResultSetHandler is a handler that gets called after a query execution.

Now, I wanted to pass as many attributes as possible, and since varargs can only be the last argument in a method call, I created VarargsUtils to do just like your ArrayTricks class.

2
  • As far as I can tell from the example code (not having used SQLQueryExecutor), you can just use the exact same built-in Java as the other answers are suggesting: Object stuff[] = { 1294, "EFT" }; System.out.println(stuff[0]); System.out.println(stuff[1]); - It correctly outputs 1294\nEFT\n
    – Izkata
    Commented Aug 15, 2013 at 1:40
  • I could, but it makes readability easier using varargs arguments, imho. Commented Aug 15, 2013 at 5:14
0

It's good, it ought to be in the standard lib. You probably should spell out "array" in full though.

I see 3 use cases for it

//1
  for(String s : array("a", "b", "c")) ...

//2
  someMethod( array(1,2), array("a", "b") );

//3
  List<String> list1 = ..., list2 = ...;
  List<String>[] lists = array( list1, list2 );
  // generic array creation and initialization
2
  • 2
    Your first one can already be written for(String s : asList("a", "b", "c")), if you import java.util.Arrays.asList.
    – ruakh
    Commented Aug 14, 2013 at 15:49
  • sure, but I don't prefer that.
    – ZhongYu
    Commented Aug 14, 2013 at 15:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.