What is "int..." in Java method's parameter? [duplicate] - java

This question already has answers here:
What is the ellipsis (...) for in this method signature?
(5 answers)
What do 3 dots next to a parameter type mean in Java?
(9 answers)
Closed 7 years ago.
I came across a method definition:
void doType(int... keyCodes) {
doType(keyCodes, 0, keyCodes.length);
}
void doType(int[] keyCodes, int offset, int length) {
if (length == 0) {
return;
}
robot.keyPress(keyCodes[offset]);
doType(keyCodes, offset + 1, length - 1);
robot.keyRelease(keyCodes[offset]);
}
The "int..." seems to indicate an indeterminate number of integer parameters but the variable is used as an array inside the function. Can someone please explain?

As you already stated correctly this java notation is to make the method accept a variable amount of (in this case) int parameter.
To handle this variable amount of variables you can access it like an array.
This functionality is introduced in java 5.
See also here:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

You are right in deducing that the ellipses indicate that this method is variadic.
When you have a variable number of potential arguments, you need some way to iterate over them - otherwise they aren't very useful in practice. Java and C# happen to have the array indexing syntax. C and C++ happen to have the va_start, va_arg and va_end macros. Different languages may have something else.
The reason why Java has the array syntax specifically is probably because it happens to match the way they are actually implemented: as a simple array parameter replaced at compile time.

Related

How to format print function in Java to print equal width per different number? [duplicate]

This question already has answers here:
Java output formatting for Strings
(6 answers)
Closed 11 months ago.
Given these variables:
int a = 1, b = 123, c = 55, d= 1231;
Is there a way in Java to print them with a set width of 5, say. In case number is less than five digits - only print dashes.
1----,123--,55---,1231-
I am aware that these can be achieved with some loops and if statements, looking for something similar to setw() from C++
System.out.println(String.format("%-5.5s", s).replace(" ", "-"));
In short, you can't do it directly. Java has functionality broadly similar to that of C's "printf" formatting.
You can set a field width, you can justify left or right, but your fill characters are limited to zero and space.
Documentation
If the format uses the general "%s" directive, and the corresponding argument is of a class under your control, then you can implement a 'formatTo' method to do the conversion. So a wrapper class might be useful to you.

get() from a List, but passing long as argument in Java [duplicate]

This question already has answers here:
Using a long as ArrayList index in java
(7 answers)
Closed 2 years ago.
I am trying to get an element from a list List<Class> listofitems, and I have a globale variable position of type long. I would like to perform listofitems.get(position) but it doesnt allow me to do so since get takes int as argument. If I want to keep the type of position as long, if there are any other way to do this? (any other way besides casting position to int)?
If you wanted to do this, you'd have to construct a class that holds a grouping of lists to represent your data. You can write your own access method that splits your long into smaller ints, to access the right position in your list.
See this answer: Using a long as ArrayList index in java
This is a point where memory must be consulted through the Unsafe api. Incase of list/arrays greater than Integer.MAX_VALUE here is the link. NOTE:
Write your own implementation of the list/array.
Unsafe is literally unsafe.
Such an implementation would require long indices.
Speed will abundant.
If what you have is a List<Class>, and it cannot be changed to another type, then there is nothing you can do besides convert that long to an int. There is no way to take an arbitrary List and call get with anything but an int.

Java function definition with brackets syntax [duplicate]

This question already has answers here:
Java Syntax: byte f()[] vs. byte[] f()
(4 answers)
Closed 3 years ago.
Was looking in the source for ByteArrayOutputStream, and I saw this function:
public synchronized byte toByteArray()[] {
return Arrays.copyOf(buf, count);
}
Where is this syntax documented? I mean the [] in front of the function. Is this the same as in declaring a regular array where the bracket can go after the name of the array or before, but in this case, the bracket can go after the function name?
String[] args;
Vs
String args[];
Edit: 2018-05-22
I found even more uses of this crazy syntax here: 10 things you didn't know about Java
#3 is where they make mention of all the ways the above syntax can be exploited
In JLS Sec 8.4:
MethodDeclarator:
Identifier ( [FormalParameterList] ) [Dims]
...
The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.

Array Length in Java - Performance [duplicate]

This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Java native array lengths
(6 answers)
Closed 9 years ago.
Let's say I create an array of ints with length 10, i.e.
int[] array = new int[10];
At some point in my code, I want to compare the value of an int variable, let's call it var, with the length of the array.
I would like to know if this piece of code:
if(var == array.length) { // stuff }
and this piece of code:
if(var == 10) { // stuff }
which do exactly the same thing, have also the same performance.
In other words, I would like to know the internal mechanics that the JVM (?) uses to find the length of the array (I don't say "to return" since length is a field, not a method). Does it make use of iteration? Because if it does, then the 2nd piece of code would be faster than the 1st one.
EDIT: Similar question regarding array.length cost (even though focusing more to its use in for loops):
What is the Cost of Calling array.length
.length is a property, so it would not do iteration for sure. Still, the value of the property is, naturally, fetched at runtime, meaning that the second solution will be a little bit faster (as this is comparison with constant).
Still the first implementation is far more preferable:
This makes your code quite more maintainable
You can alter the length of the array only at one place
You will never feel the performance difference unless you pass through this if litterally millions of times in a second.
EDIT By the way you can yourself tell this is a property - there are no braces after the call. I at least do not know of a way in java to make property access do additional computation, but just retrieving its value.
.length is a property of the array, not a function. Thus, the result would be available immediately, with no iteration necessary.
From the Java Doc
The members of an array type are all of the following:
The public final field length, which contains the number of components
of the array. length may be positive or zero.
length is an final field of array, so no iterations are required while writing following code.
if(var == array.length) { // stuff }
And it is good coding practice indeed.
The length property of an array is extracted in constant (O(1)) time - there is no iteration needed. It's also good practice to use this.

variable/parameterized width for printf/format in Java (using * or something else?) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java printf using variable field size?
I haven't worked with Java in a while so I was looking for a way to
specify variable width in format/printf when formatting/printing output. My example shows the use with an integer, but of course I'd like this to work for other types too.
E.g., something along the lines of
int val = 8;
int wid = 5;
System.out.printf("%"*d\n", wid, val);
I could use this work-around, which is ugly:
System.out.printf("%"+wid+"d\n", val);
Was the * variable field width specifier removed from Java? This old'ish
page, section 1.3.1,
shows the use (like it would be used in C), but I can't get it to
work, resulting in:
java.util.UnknownFormatConversionException: Conversion = '*'
nor have I been able to find more recent references that this
does work.
Is there an easier way to do this other than my work-around above?
I did look around before posting and came across this about 2-year old SO question Java printf using variable field size? but is that the final word on this?
The general syntax of a format specifier is
%[parameter][flags][width][.precision][length]type
Instead of printf, you can also use
String.format("%"+wid+"d",val);
And yes, these are the only ways in case you are using a Java Formatter.

Categories