Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hardcode an Array in a For Loop

Tags:

java

I am trying to write a Java class which needs to be as short as possible (line-wise). Within my class, I have the following code:

char[] myArray = {'a', 'b', 'c', 'd'};
for(char c : myArray) ...

In order to make this shorter, as I will always be iterating over the same chars, I thought that I might be able to do something like this:

for(char c : {'a', 'b', 'c', 'd'}) ...

However, this doesn't work and I cannot find anything online to show me how to do this (I'm not really sure what to search for this).

Is this possible in a different way? Or can this not be made any shorter?

like image 302
Haych Avatar asked Aug 11 '26 17:08

Haych


1 Answers

You need the type identifier for the array aswell as

for(char c : new char[] {'a', 'b', 'c', 'd'})  {
   ...      
}
like image 96
SomeJavaGuy Avatar answered Aug 13 '26 08:08

SomeJavaGuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!