3 ms·
Instead of: public int[] filterEven(int[] array) { aggregator = int[array.size()] for(int i: array) { int aggregatorSize = 0; // The n
by srgseg 16y ago
Instead of:
public int[] filterEven(int[] array) {
aggregator = int[array.size()]
for(int i: array) {
int aggregatorSize = 0;
// The next line is the only unique part of
// this function!
if(array[i] % 2 == 0) {
// Someone please tell me there's an easier way
// to append to an array than this
aggregator[aggregatorSize] = array[i];
aggregatorSize += 1;
}
}
}
int[] array = { 1, 2, 3, 4, 5, 6 };
filterEven(array);
// => { 2, 4, 6 }
in Java, you'd normally use collections and not arrays.
So it'd be:
List<Integer> result = new ArrayList<Integer>();
for(int i : argument) if(i%2==0) result.add(i);
So it's really 2 lines, not 7.
And if you really needed to work on an argument passed in the form of a primitive array, you'd use Arrays.asList(arrayArgument) to easily turn the array into a list.
Java really shines when you are doing multithreaded code because you have a rich set of thread safe collections. (e.g. multiple simultaneous requests in a web app all modifying shared data structures).
With reading something into a file, anyone that does this often will just use a library (either their own or a 3rd party one).
Thus, they'd just do:
String data = FileUtil.readFile("abc.txt");
- djacobs 16y agoDuly noted. I asked for alternatives because idiomatic Java eludes me. Thanks.
- chrisbroadfoot 16y agoAgreed. A lot of complaints about Java are because of shit APIs (standard library) rather than the language itself. It's certainly possible to write beautiful code in Java, it's just not very common :) One thing that Java could benefit from greatly would be type inference. That alone would remove so much syntactical noise. Honestly, who cares that you need to write a Main class? This is quite commonplace, and only really inhibits scripting tasks. In any real application, this is a non-issue.