Content deleted Content added
note about inaccuracy in java generics section, with example program. |
|||
Line 697:
[[User:Aquishix|Aquishix]] ([[User talk:Aquishix|talk]]) 12:19, 10 February 2014 (UTC)
== Java Generics Inaccuracy ==
I believe there is an error in the generics vs. templates comparison section.
It says (as of 11/18/2015):
{| class="wikitable"
! '''C++ Templates''' !! '''Java Generics'''
|-
| Templates can be specialized—a separate implementation could be provided for a particular template parameter.
|| Generics cannot be specialized.
|}
The below program shows an example of specializing a generic method for a specific template parameter. The "myCount" method is specialized for subclasses (inclusive) of Character. Is this not "providing a separate implementation for a particular template parameter"? It seems to precisely match the definition of "Explicit template specialization" given here: [[Wikipedia:Template (C++)#Explicit Template Specialization]]
<syntaxhighlight lang="java">
import java.util.*;
public class Test {
static <T> int myCount (Iterator<T> iterator, T val)
{
int ret = 0;
while (iterator.hasNext()) {
T entry = iterator.next();
if (entry.equals(val)) ++ret;
}
return ret;
}
static <T extends Character> int myCount (Iterator<T> iterator, T val)
{
System.out.println("weirdcount");
int ret = 0;
while (iterator.hasNext()) {
T entry = iterator.next();
if (entry.equals(val)) ++ret;
}
return ret*3;
}
public static void main (String[] args) {
List<Integer> nums = new ArrayList<>(Arrays.asList(1,2,3,3,3,4,5,2,1));
int count = myCount(nums.iterator(), 3);
System.out.println(count);
List<Character> characters =
new ArrayList<>(Arrays.asList('a','b','c','d','e','a','b'));
int count2 = myCount(characters.iterator(), 'a');
System.out.println(count2);
}
}
</syntaxhighlight>
Thanks,
[[User:Vancan1ty|Vancan1ty]] ([[User talk:Vancan1ty|talk]]) 04:35, 19 November 2015 (UTC)
|