Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Comparison of C Sharp and Java
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Fibonacci sequence === This example illustrates how the [[Fibonacci sequence]] can be implemented using the two languages. The C# version takes advantage of C# [[#Generator methods|generator methods]]. The Java version takes the advantage of {{mono|Stream}} interface and method references. Both the Java and the C# examples use [[K&R style]] for code formatting of classes, methods and statements. {| style="width:100%; border:none;" class="wikitable" |- !Java !C# |- |width=50%|<syntaxhighlight lang=Java style="font-size:90%"> // The Fibonacci sequence Stream.generate(new Supplier<Integer>() { int a = 0; int b = 1; public Integer get() { int temp = a; a = b; b = a + temp; return temp; } }).limit(10).forEach(System.out::println); </syntaxhighlight> |width=50% valign=top|<syntaxhighlight lang="csharp" style="font-size:90%"> // The Fibonacci sequence public IEnumerable<int> Fibonacci() { int a = 0; int b = 1; while (true) { yield return a; (a, b) = (b, a + b); } } </syntaxhighlight> |- |width=50%| |width=50% valign=top|<syntaxhighlight lang="csharp" style="font-size:90%"> // print the 10 first Fibonacci numbers foreach (var it in Fibonacci().Take(10)) { Console.WriteLine(it); } </syntaxhighlight> |- valign="top" |Notes for the Java version: * The Java 8 Stream interface is a sequence of elements supporting sequential and parallel aggregate operations. * The generate method returns an infinite sequential unordered stream where each element is generated by the provided Supplier. * The limit method returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. * The forEach method performs an action for each element of this stream, this action could be a lambda or a method reference. ====Using a foreach==== The same example above, but using a method returning an Iterable to maintain greater similarity with the C# example. Anything that implements the iterable interface can be iterated in a foreach. <syntaxhighlight lang="java" style="font-size:90%"> Iterable<Integer> fibonacci(int limit) { return Stream.generate(new Supplier<Integer>() { int a = 0; int b = 1; public Integer get() { int temp = a; a = b; b = a + temp; return temp; } }).limit(limit)::iterator; } </syntaxhighlight> <syntaxhighlight lang="java" style="font-size:90%"> // print the 10 first Fibonacci numbers for(int it: fibonacci(10)) { System.out.println(it); } </syntaxhighlight> The most common way to do the example above would be to use Streams, not Iterables. This could be returned from a method like the C# example, but it's unnecessary and could be used directly by just collecting the Stream. Below is an example using Streams and the collecting the Stream calling {{mono|toList}} in the foreach block. <syntaxhighlight lang="java" style="font-size:90%"> var fibonacci = Stream.generate(new Supplier<Integer>() { int a = 0; int b = 1; public Integer get() { int temp = a; a = b; b = a + temp; return temp; } }); </syntaxhighlight> <syntaxhighlight lang="java" style="font-size:90%"> // print the 10 first Fibonacci numbers for(int it: fibonacci.limit(10).toList()) { System.out.println(it); } </syntaxhighlight> In addition to the toList collector in the foreach block, It's important to highlight that there are more collectors for every type of collection. Also, custom collectors could be created by implementing the {{mono|Collector}} interface or describing the implementation as a lambda expression, both cases passing it as arguments to the collect method of the {{mono|Stream}} object. In this example would be just calling the {{mono|collect}} method instead {{mono|toList}} if would have some complex type of object per item for the collection. Both examples could also be done with {{mono|IntStream}} and {{mono|IntSupplier}} and avoid the {{mono|Integer}} generic in the {{mono|Supplier}} interface implementation, but the generic is used to preserve greater similarity with the C# example. ====Functional Style==== The above algorithm can be written even more consistently, using {{code|Stream.iterate}}. The iterate method receives a seed parameter, and a function that specifies what to do for each iteration. In this case, the seed can be a record class with the 2 initial values of the algorithm, and its respective transformation in each iteration. In short, the iterate method makes unnecessary the implementation of a Supplier. <syntaxhighlight lang="java" style="font-size:90%"> record Pair(int a, int b) {}; Stream .iterate(new Pair(0, 1), p -> new Pair(p.b, p.a + p.b)) .limit(10) .map(p -> p.a) .forEach(System.out::println); </syntaxhighlight> |Notes for the C# version: * The method is defined as returning instances of the interface {{csharp|IEnumerable<int>}}, which allows client code to repeatedly request the next number of a sequence. * The {{csharp|yield}} keyword converts the method into a generator method. * The {{csharp|yield return}} statement returns the next number of the sequence and creates a continuation so that subsequent invocations of the {{csharp|IEnumerable}} interface's {{csharp|MoveNext}} method will continue execution from the following statement with all local variables intact. * Tuple-assignment avoids the need to create and use a temporary variable when updating the values of the variables {{mono|a}} and {{mono|b}}. |}
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)