Any Way to Declare an Array In-Line

Any way to declare an array in-line?

m(new String[]{"blah", "hey", "yo"});

Inline Array Definition in Java

You could create the int[] array in the for loop.

for (int i : new int[] {1, 2, 3, 4, 5}) {
...
}

Here you are making an anonymous int array, which is the closest thing to what you want. You could also loop through a Collection.

Note that this question has nothing to do with OOP. It's merely a matter of syntax. Java supports anonymous arrays/objects just like C++.

Why can't I create a new Java array inline?

bar.setArray(new String[] { "foo" });

I believe this format is required because Java does not want to imply the array type. With the array initialization format, the type is defined explicitly by the assigned variable's type. Inline, the array type cannot be inferred.

Can't use an inline array in C#?

You have to create the array first, using new[].

string letter = (new[] {"a","b","c"}).AnyOne();

As @hvd mentioned you can do this without parantheses (..), I added the parantheses because I think it's more readable.

string letter = new[] {"a","b","c"}.AnyOne();

And you can specify the data type new string[] as on other answers has been mentioned.


You can't just do {"a","b","c"}, because you can think of it as a way to populate the array, not to create it.

Another reason will be that the compiler will be confused, won't know what to create, for example, a string[]{ .. } or a List<string>{ .. }.

Using just new[] compiler can know by data type (".."), between {..}, what you want (string). The essential part is [], that means you want an array.

You can't even create an empty array with new[].

string[] array = new []{ }; // Error: No best type found for implicity-typed array

Inline function filling an array

You could use the following:

List<String> names = IntStream.range(0, 10)
.boxed()
.map(i -> String.format("Name %d", i))
.collect(Collectors.toList())

Hopefully syntax is fine there but you get the idea.

declare and initialize an array of pointers to function in 2 lines in c

What's wrong with breaking down the statement to use more than one line?

void (*tfnc[8]) (va_list *, s_struct *) 
= {conv_c, conv_s, conv_p, conv_id, conv_id, conv_u, conv_x, conv_X};

What is the way of declaring an array in JavaScript?

The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:

function Array() { return []; }

alert(Array(1, 2, 3)); // An empty alert box

However, the larger issue is that of consistency. Someone refactoring code could come across this function:

function fetchValue(n) {
var arr = new Array(1, 2, 3);

return arr[n];
}

As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:

var arr = new Array(1);

Is it faster (or better) to declare an array inline in Java?

Which form is the fastest? Depends on the JIT - it's possible they're equivalent. Very few, if any, programs will ever notice the difference if there is any.

Which form is the best? Almost invariably, the one that leaves your program more readable.

But is there any actual difference, regardless of if we'll ever notice? Let's have a look!

class ArrayTest {

public int[] withNew() {
int[] arr = new int[4];
return arr;
}

public int[] withInitializer() {
int[] arr = {0, 0, 0, 0};
return arr;
}

}

We disassemble this with javap -c ArrayTest:

Compiled from "ArrayTest.java"
class ArrayTest {
ArrayTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

public int[] withNew();
Code:
0: iconst_4
1: newarray int
3: astore_1
4: aload_1
5: areturn

public int[] withInitializer();
Code:
0: iconst_4
1: newarray int
3: dup
4: iconst_0
5: iconst_0
6: iastore
7: dup
8: iconst_1
9: iconst_0
10: iastore
11: dup
12: iconst_2
13: iconst_0
14: iastore
15: dup
16: iconst_3
17: iconst_0
18: iastore
19: astore_1
20: aload_1
21: areturn
}

Nope, they're not the same in this case - using the initializer form causes the slots to be individually set to 0, which is kind of pointless since they're already zeroed by the array allocation. So, it's basically equivalent to this:

public int[] withNewAndSettingExplicitly() {
int[] arr = new int[4];
arr[0] = 0;
arr[1] = 0;
arr[2] = 0;
arr[3] = 0;
return arr;
}

although that compiles to yet another set of byte code, which is mostly the same but not quite:

  public int[] withNewAndSettingExplicitly();
Code:
0: iconst_4
1: newarray int
3: astore_1
4: aload_1
5: iconst_0
6: iconst_0
7: iastore
8: aload_1
9: iconst_1
10: iconst_0
11: iastore
12: aload_1
13: iconst_2
14: iconst_0
15: iastore
16: aload_1
17: iconst_3
18: iconst_0
19: iastore
20: aload_1
21: areturn

Thus, the moral of the story is this: If you want all elements set to 0, you're generating less bytecode with new int[size] (which may or may not be faster), but you also have to type less (which imho is a big win). If you want to set the values in the array directly when you're allocating it, use whatever looks best in your code, because the generated code will be pretty much the same whatever form you choose.

Now, to answer your actual questions:

Does Method2 operate any faster (or differently) by avoiding the call to "new"?

As we saw, the new is just hidden behind the initializer syntax (look for the newarray op code). By the way, allocation is extremely cheap in the JVM (generational garbage collectors have that pleasant side effect).

Or are the two implementations above equivalent?

As we saw - not quite, but it's unlikely anyone will ever notice the difference.

In either case, can the Java compiler or runtime make an optimization to avoid the overhead of hitting the memory allocator for this short-lived temporary buffer?

Again - allocation is cheap, so don't worry. Nevertheless, recent JVMs have this little feature called escape analysis which may result in the array being stack allocated rather than heap allocated.

How to declare an array inline in VB.NET

Dim strings() As String = {"abc", "def", "ghi"}

C Declare and define quickly the fields of an array

var.array = (uint8_t)[]{0,1,2,3,4,5,6};

Do you mean a compound literal?

then the syntax is (uint8_t []) instead of (uint8_t)[]

But you can not assign to an array (Why are arrays not lvalues).

Your first example is almost correct:

memcpy(var.array, (uint8_t){0,1,2,3,4,5,6}, 7);

but again, use the correct syntax:

memcpy(var.array, (uint8_t []){0,1,2,3,4,5,6}, 7);


Related Topics



Leave a reply



Submit