I need to pass an empty int array.
new int[]{} -> this works.
But, is there anyway with the below approach?
Collections.emptyList().toArray() -> I am unable to cast this to int[] array.
The method signature,
public void checkVersions(final int[] versions)
This is the method to be called. There are case where i need to pass some empty int[].
Thanks
This might be considered off-topic to the question, but I still want to provide you with the following thougts:
When you write code, you should write it in a way that makes it as simple as possible to read later on by somebody who has no clue what the code is supposed to do.
Therefore, "new int[0]" or "new int[]{}" are much better than "IntStream.empty().toArray()". Why? Because the first two make it clear that you are constructing an int[] and that it is empty. The later solution with the IntStream requires more thought (thus has higher cognitive load) as you first see the IntStream, of which and empty stream is created. This empty stream of integers is then converted to an array. So you don't see the data type that is being created and you have an extra step (the conversion).
I would rate (personal thought!) other solutions than "new int[0]" or "new int[]{}" to be tricky code. Don't try to be fancy with a plain "empty integer array" creation, it will just cause pain to anybody who reads the code.
Now, I don't want to talk bad about you interest in alternatives, I only want to avoid that you put such code into production. I hope this message came along.
try this one
int[] array = IntStream.empty().toArray();
Related
I have the following code
//assume we have a list of custom type "details" already constructed
for(int i = 0; i < details.size(); ++i) {
CallerID number = details.get(i).getNextNumber();
ClientData.addToClient(number);
}
I have oversimplified the code. The enum CallerID and the ClientData object work as intended. I am asking for help converting this loop to a lambda function so I can understand the logic of how to do so, then fill in the appropriate code as needed.
Let's first write it as a modern basic for loop and golf it a bit, just so we're comparing apples to apples:
for (var detail : details) clientData.addToClient(detail.getNextNumber());
And this is probably the right answer. It is local var, exception, and control flow transparent (which is what you want), and short.
The lambda form is this, but it's got downsides (mostly, those transparencies). It also isn't any shorter. You shouldn't write it this way.
details.stream().forEach(d -> clientData.addToClient(detail.getNextNumber());
You may be able to just remove stream() from that. But probably not.
Generally when people say "I want it in lambda form", that's not because someone is holding a gun to your head - you are saying that because somebody peddling a religion of sorts to you told you that 'it was better' and that this 'will scale'. Realize that they are full of it. There can be advantages to 'functional style', but none of these snippets are functional. A true functional style would involve a bunch of side-effect-free transformations, and then returning something.
.addToClient? You've lost the functional game there - you would want to instead convert each detail to something (presumably a ClientID), and from there construct an immutable object from that stream. You'd 'collect' your ClientIDs into a clientData object.
Let's say for example that clientData is just a 'list of ClientIDs' and nothing more. Then you'd write something like this:
var clientData = details.stream()
.map(MyDetailClass::getNextNumber)
.collect(Collectors.toList());
Is this better? No. However, if you're looking for 'a stream-style, lambda-based functional take on things', that qualifies. The output is constructed by way of collection (and not forEach that does a side-effect operation), and all elements involved are (or can be) immutable.
There's no particular reason why you'd want this, but if for some reason you're convinced this is better, now you know what you want to do. "Just replace it with a lambda" doesn't make it 'functional'.
I am asking for help converting this loop to a lambda function so I can understand the logic of how to do so, then fill in the appropriate code as needed.
A Function returns a value. As you are just updating something what you need is a Consumer which accepts a single argument of a list of some detail. Assuming those are in a Class named SomeDetails, here is how you would do it.
As you iterating over some structure limited by size and using get(i) I am presuming a list is required here.
List<SomeDetails> details = new ArrayList<>(); // then populated
// lambda definition
Consumer<List<SomeDetails>> update = (lst)-> {
for(SomeDetails detail : lst) {
CallerID number = detail.getNextNumber();
ClientData.addToClient(number);
}
};
And then invoke it like this, passing the List.
update.accept(details);
All the above does is encapsulate the for loop (using the enhanced version for simplicity) and perform the operation.
If this is all you wanted, I would recommend just doing it as you were doing it sans the lambda.
I have this method:
//not related to the error, but included for reference
ArrayList<ArrayList<Color>> a = new ArrayList<ArrayList<Color>>();
void addColorToList(float[] j) //this array always length 3
{
float[] k = Arrays.copyOf(j, 3);
Arrays.sort(k);
//Error in the following line
a.get(Arrays.asList(j).indexOf(k[0])).add(new Color(j[0], j[1], j[2]));
}
and this error:
Exception in thread "AWT-EventQueue-1"
java.lang.ArrayIndexOutOfBoundsException: -1
I've determined that my code always calls a.get() with -1, because Arrays.asList(j). indexOf(k[0]) does not find the element. However, I cannot figure out why this doesn't work as I would expect it to. I tried printing out the result of Arrays.asList(j), but I'm not really sure what to make of the result: [[F#307af497]. Can anybody tell me what the issue is?
Lets start with this:
I tried printing out the result of Arrays.asList(j), but I'm not really sure what to make of the result: [[F#307af497].
You are printing a list using (effectively) the toString() method. So ...
The outer '[' and ']' are from the list formatting.
You have a list consisting of one element.
That element is an array of float. (The [F#307af497 is produced by Object.toString(), and [F is how the type float[] is rendered ...)
This is actually an important clue. Arrays.asList(float[]) is returning a "list of float[]" ...
But why?
Well, because that's what it is supposed to do!!
The Arrays.asList signature is Arrays.asList<T>(T ...). That means it expects either an explicit T[] ... or a sequence of zero or more T instances, which it will then wrap as an Object[]. The Object[] is then wrapped as a List<Object> (roughly speaking).
The critical thing here is that the actual type T must be a reference type ... not a primitive type.
But your code seems to be expecting an overloaded method like this Arrays.asList(float ...) ... and expecting that that will give you your float[] wrapped as a List<Float>.
Unfortunately, there is no such overload for asList.
So what is actually happening is that:
your call is binding to Arrays.asList<float[]>(float[] ...)
the varargs is causing j to be wrapped in an array; i.e. equivalent to new float[][]{j}
the result is an instance of List<float[]> ... with one element.
So what is the solution?
In general ...
One solution would be to represent your floats as a Float[] rather than a float[]. Ideally, you would push this change back through the code that created the array in the first place, etcetera.
A second solution would be to convert the float[] to a Float[] before calling asList. The simple way to do that is with a simple loop. (There may also be a 3rd-party library for doing this.) The downsides are:
the conversion needs to happen each time you call this method which could be expensive if you call it a lot, and
there is no connection between the original array and the array that you have wrapped ... if you wanted to update the array through the list wrapper.
But in this case, the best solution is to simply replace this:
Arrays.asList(j).indexOf(k[0])
with a simple loop that iterates over the original float[] testing for an entry that matches k[0].
The moral of this story: you can easily shoot yourself in the foot by striving for an elegant solution in Java.
Often, dumb code is better. (Both faster, and more correct.)
As part of my AP curriculum I am learning java and while working on a project I wondered which of the following is best way to return a value?
public double getQuarters(){
return quarters;
}
or
public void getQuarters(){
System.out.println(quarters);
}
***Note: I now that the second option is not "technically" returning a value but its still showing my the value so why bother?
Your answer would be correct. The second method doesn't return any value at all, so while you might be able to see the output, your program can't. The second method could still be useful for testing or even for a command line application, but it should be named something like printQuarters instead.
public double getQuarters(){
return quarters;
}
Use this incorder to encapsulate quarters and hide it from being accessed by other programs. That means, you have to declare it as private quarters. Let see the second option:
public void getQuarters(){
System.out.println(quarters);
}
However, this seems wrong as getQuarters is not returning anything. Hence it would make more sense to refactor it as
public void printQuarters(){
System.out.println(quarters);
}
You answered your own question. For most definitions of the word "best", you should go with the first option.
Your question, however, does touch on the object-oriented programming topic of accessors and mutators. In your example, "getQuarters" is an accessor. It is usually best to use accessors to retrieve your values. This is one way to adhere to the Open/Closed Principle.
Also, the Java community has a coding convention for this and many tools and libraries depend on code following those conventions.
If all you need to do is display the value when this method is called, and you are ok with console output, then your System.out.println method will do the job. HOWEVER, a function that actually returns the variable is much more semantically correct and useful.
For example, while you may only need to print the variable for your current project, what if you came back later and decided that you were instead going to output your variable to a file? If you wrote your getQuarters function with a println statement, you would need to rewrite the whole thing. On the other hand, if you wrote the function as a return, you wouldn't need to change anything. All you'd have to do is add new code for the file output, and consume the function where needed.
A returning function is therefore much more versatile, although more so in larger code projects.
You return values to a specific point in your program, so that the program can use it to function.
You print values at a specific point in your program, so that you as an end user can see what value you got back for some function.
Depending on the function - for instance, yours - the result of quarters is no longer regarded in the program; all it did was print a value to the screen, and the application doesn't have a [clean|easy] way to get that back to use it.
If your program needs the value to function, then it must be a return. If you need to debug, then you can use System.out.println() where necessary.
However, more times than not, you will be using the return statement.
Option 1 is far superior.
It can be easily Unit Tested.
What if the spec changes and sometimes you want to print the result, other times put it into a database? Option 1 splits apart the logic of obtaining the value from what to do with it. Now, for a single method getQuarters no big deal, but eventually you may have getDimes, getEuros, etc...
What if there may be an error condition on quarters, like the value is illegal? In option 1, you could return a "special" value, like -1.0, or throw an Exception. The client then decides what to do.
For example given the following methods:
public double[] getCoord(){
return coord;
}
public double getCoord(int variable){
return coord[variable];
}
Would it be better to call
object.getCoord()[1]
or
object.getCoord(1)
and why?
Although there is no performance difference, the second method presents a far superior API, because Java arrays are always mutable. The first API lets your users write
object.getCoord()[1] = 12.345;
and modify internals of your object behind your back. This is never a good thing: even a non-malicious users could do things you never intended, simply by mistake.
In terms of performance, it doesn't matter. The first method returns a reference to the array, not a copy.
That said, the second method protects the array from being modified outside the class.
No, Java doesn't read the whole array when you use the subscript operator ([]). With regards to would it be better to use the accessor method to grab the array first, then index into it versus call a method that does the same thing, it's probably negligible. You're still incurring the overhead (minimal mind you) of invoking a function and returning a result either way.
I am going to guess that #2 is marginally slower because a parameter has to be pushed onto the stack prior to the call to getCoord(int). Not much in it though.
Neither has to read the whole array.
Both are slower than direct array access, for example coord[1].
I have a method that takes 5 double values and performs an action with them. Right now the argument list is five different doubles. Is there any way to pass a double[] as an argument to the method but make sure its length is exactly 5?
One way is this:
private void myMethod(double[] args) {
if (args.length == 5) {
// do something
}
}
but is there a better way?
If you know you need exactly 5 doubles, then I think you are better off asking for 5 distinct doubles. Having them listed out with meaningful names it will still be hard enough (even with intellisense or whatever it's called) to keep the order of the variables straight. If they are in an array, the user will need to consult the documentation to see which value should go in which index.
No. You can't restrict the length of an array passed to a function.
If your goal is to keep the checking code out of the method so it's cleaner, you could delegate the real work to another method.
If your concern is the length of the parameter list you could pass a parameter object.
You could create a class which is a specialization of a Vector limited to 5 doubles, but it seems like overkill. I would just throw an exception if there are too few or too many entries in the array - this is likely a programming problem rather than a runtime exception.
You could put your code in try-catch block. This provides to miss an unnecessary check.
But if something doing wrong you could avoid the problems with exception.