Generics
The new versions of .NET (2.0) and Java (1.5) provide a new construct called Generics. I have been testing both and here is some code that I wrote to test and compare.
.NET:
using System;
using System.Collections.Generic;
using System.Text;class linkedListNode
{
private linkedListNode next = null;
private NodeType value;public linkedListNode(NodeType value)
{
this.value = value;
}public void link(linkedListNode element)
{
if (next != null)
{
next.link(element);
}
else
{
next = element;
}
}public void print()
{
if (value != null)
{
System.Console.WriteLine(value.ToString());
}
else
{
System.Console.WriteLine(“Empty node.”);
}if (next == null)
{
System.Console.WriteLine(“Last node.”);
}
else
{
next.print();
}
}
}class linkedList
{
private linkedListNode root = null;public void add(NodeType element)
{
linkedListNode node = new linkedListNode(element);if (root != null)
{
root.link(node);
}
else
{
root = node;
}
}public void print()
{
System.Console.WriteLine(“The list is a list of ” + root.GetType().ToString());
root.print();
}
}class thingy
{
private String text;public thingy(String text)
{
this.text = text;
}public override String ToString()
{
return text;
}
}public class test
{
public static void Main()
{
linkedList list = new linkedList();
thingy t;
t = new thingy(“t1”);
list.add(t);
t = new thingy(“t2”);
list.add(t);
list.print();
System.Console.ReadLine();
}
}
Java:
class linkedListNode<NodeType>
{
private linkedListNode next = null;
private NodeType value;public linkedListNode(NodeType value)
{
this.value = value;
}public void link(linkedListNode<NodeType> element)
{
if(next != null)
{
next.link(element);
}
else
{
next = element;
}
}public void print()
{
if(value != null)
{
System.out.println(value.toString());
}
else
{
System.out.println(“Empty node.”);
}if(next == null)
{
System.out.println(“Last node.”);
}
else
{
next.print();
}
}
}class linkedList<NodeType>
{
private linkedListNode root = null;public void add(NodeType element)
{
linkedListNode<NodeType> node = new linkedListNode<NodeType>(element);
if(root != null)
{
root.link(node);
}
else
{
root = node;
}
}public void print()
{
System.out.println(“The list is a list of ” + root.getClass().getName());
root.print();
}
}class thingy
{
private String text;public thingy(String text)
{
this.text = text;
}public String toString()
{
return text;
}
}public class test
{
public static void main(String[] args)
{
linkedList<thingy> list = new linkedList<thingy>();
thingy t;
t = new thingy(“t1”);
list.add(t);
t = new thingy(“t2”);
list.add(t);
list.print();
}
}
Some interesting points:
- C# syntax almost equal to Java syntax
- The output is different; Java loses type information
- The lost type information is also visible when compiling.