VS: Restore Missing Auto Window

Somehow, the Auto-Window in my MS VisualStudio 2005 vanished and I couldn’t get it back. MS says, it is available in the Debug/Windows-Menu. But it wasn’t for me. See this screenshot as evidence:

>Auto-1

After some time of searching the web without success, I had the saving idea. So…

This is how to get back a missing Auto window in VS2005:

  • Make sure you are in debugging mode.
  • In the menu, select Extras/Customize.
  • In the upcoming dialog select category Debugging.
    >Auto-2
  • On the right, look for Auto and drag the icon to a toolbar and drop it there.
  • Close the Customize dialog.
  • Press the new button on the toolbar. It is only active, if you are in debugging mode.
  • Eureka! The Auto window is back!

Java for C# Programmers 11: Algorithms

Algorithms

In Java, there are many algorithms available as static methods of the Collections class. I’m giving here examples for the most important ones.

    import java.util.Collections;    
    List numbers = new ArrayList();
    numbers.add(1);
    numbers.add(5);
    numbers.add(4);                 // 1 5 4
    Collections.sort(numbers);      // 1 4 5
    Collections.reverse(numbers);   // 5 4 1
    Collections.shuffle(numbers);   // 4 1 5
    Collections.swap(numbers, 0, 2);   // 5 1 4
    Collections.fill(numbers, 7);      // 7 7 7

    List num2 = new ArrayList();
    Collections.addAll(num2,  2, 6, 5);    // 2 6 5

    Collections.copy(numbers, num2);    // numbers is 2 6 5
    Collections.sort(num2);     // 2 5 6
    num2.add(7);            // 2 5 6 7
    Collections.rotate(num2, 1);     // 7 2 5 6 
    Collections.rotate(num2, -1);    // 2 5 6 7      
    int pos = Collections.binarySearch(num2, 5);    // pos is 1

    pos = Collections.binarySearch(num2, 3);    
        // -> pos is -2. pos is (-(insertion_point) - 1), if the 
        // element is not contained in the collection. 
        // Therefore you can add an element to a collection
        // with a line like the following. 
    num2.add(-pos-1, 3);        //  2 3 5 6 7

    pos = Collections.binarySearch(num2, -8);   // pos is -1
    num2.add(-pos-1, -8);           //  -8 2 3 5 6 7

    Collections.shuffle(num2);      // 2 3 -8 5 7 6
    int n = Collections.min(num2);  // -8 
    int m = Collections.max(num2);  // 7 
    boolean b = num2.contains(3);   // true 

    b = num2.contains(4);           // false
    b = num2.containsAll(numbers);      // true;    
    numbers.add(11);        
    b = num2.containsAll(numbers);      // false;   

    b = Collections.disjoint(num2, numbers); // false
    numbers.clear();        // numbers is empty
    Collections.addAll(numbers, 11, 9, 1);  // 11 9 1
    b = Collections.disjoint(num2, numbers);    // true

    numbers.add(11);                            // 11 9 1 11 
    n = Collections.frequency(numbers, 11);     // 2

    Collections.copy(numbers, num2);    
      // -> IndexOutOfBoundsException: Source does not fit in dest 

UnsupportedOperationException

Gotcha: In Java, it may be that a collection has the Collection interface but does not really implement it. This is true especially for unmodifiable collections. In these cases, it is common practice that all methods that are not really implemented throw UnsupportedOperationException.

Converting Arrays to Lists And Vice Versa

As arrays and Iterables do not have a common base, you sometimes will need to convert an array to an Iterable and vice versa.

Array to Iterable

To use an array in a function, where a List or an Iterable is required, you can create a fixed-size List from the array. Such a fixed-size List is no real List, it is just a wrapper around the array and has a List interface.

Gotcha: This interface is not implemented out. Only reading functions are implemented. All the others throw UnsupportedOperationException.

void a(Iterable list)
{
    for(int i: ll)
        System.out.printf(" %d", i);
}

Integer[] h4 = {4, 5, 11, 46};
a(h4);      // Compile error: The method a(Iterable)
            // is not applicable for the arguments (Integer[])  

List ll = Arrays.asList(h4);
a(ll);      // ok,   4 5 11 46

ll.add(4711) // **GOTCHA** throws UnsupportedOperationException 

Probably it is safer to use only the Iterable interface with
the asList function:

Iterable l2 = Arrays.asList(h4);
a(l2);       // ok,   4 5 11 46

l2.add(4711) // Compile error: The method add(int) is 
             // undefined for the type Iterable    

If you need a List with variable size, use the following construct. This will copy the array into a List and not only create a wrapper.

List ll = new ArrayList(Arrays.asList(h4));
ll.add(4711); // ok
a(ll);     // 4 5 11 46 4711

List to Array

ToArray Method

Sometimes, you may need an array but you have a List. Imagine you must use this function:

static void b(Integer[] ll)
{
    for (int i : ll)
        System.out.printf("%d ", i);
}

And you have a List.

List h5 = new ArrayList();
h5.add(89);
h5.add(76);

Then you can create an array of Integer like this.

Integer[] h6 = new Integer[h5.size()];
h5.toArray(h6);

b(h6);  // 89 76

Manual Method

If you have got a function which needs an int[] array like this

    static void a(int[] ll)
    {
        for (int i : ll)
            System.out.printf("%d ", i);
    }

And you have a List like above, then you can of course create an array of int like this:

    int[] h7 = new int[ts.size()];
    for (int i = 0; i < ts.size(); ++i)
        h7[i] = ts.get(i);

    a(h7);    // 89 76

Java for C# Programmers 10: Collections

Collections

Collections in Java involve several inconsistencies which seem quite odd for a C# developer. To understand some of the oddities of Java collections, you should keep in mind that Java is an old framework and at some points in its evolution, some new paradigms have been introduced and some old paradigms have been changed.

Before Java 5, you had collections that had Object as contained type. Later Java versions have generic collections and generic collection-interfaces. I’ll talk only about the generics here, but am leaving away the mostly.

Collection Interfaces

Modern Java collection handling is based completely on generic interfaces. The basic interface for collections is Collection.

From Collection derived interfaces are

List, Set, Queue, Deque, SortedSet, NavigableSet and the thread-safe interfaces concurrent.BlockingQueue, concurrent.BlockingDeque, concurrent.TransferQueue.

The following table shows the interfaces and the implementations available in Java SE 7. The names are mostly self-explanatory but where needed, some explanations are given under the table.

Interface Implementing Class C# Analogon
Collection All of the following ICollection
List LinkedList, ArrayList, Vector, Stack IList
Set HashSet, TreeSet, LinkedHashSet ISet
Queue ArrayDeque, LinkedList Queue class
Deque ArrayDeque, LinkedList LinkedList class
  • ArrayList and Vector are nearly the same, the main difference is that Vector is synchronized and ArrayList is not.
  • Stack extends Vector and so is synchronized, too.
  • LinkedHashSet is implemented as a hash table with an added linked list. The linked list orders its elements in the order the elements have been added to the LinkedHashSet.

Map Interface

The Map interface is equivalent to C#’s IDictionary. Map is the base interface of these extended interfaces: SortedMap, NavigableMap, concurrent.ConcurrentMap and concurrent.ConcurrentNavigableMap.

Gotcha: Strange, but true: a Map is not a Collection in Java.

HashMap, Hashtable, TreeMap, WeakHashMap, Properties and LinkedHashMap are the most important implementations of the Map interface.

  • The difference between Hashtable and HashMap is: Hashtable is synchronized, HashMap is not.
  • A TreeMap is implemented as tree. It is ordered by key.
  • LinkedHashMap keeps a linked list which is ordered by the order of insertion of elements into the list.
  • A WeakHashMap stores keys as weak references. The C# analogon to a WeakHashMap is a Dictionary>.
    Gotcha: The WeakHashMap automatically removes an entry if the entry’s key is garbage collected. Of course, a Dictionary> does not remove entries automatically.
  • Properties can be used for ini-files.

Map Example

Map h = new HashMap();

h.put(20097, "Hamburg");
h.put(76307, "Karlsbad-Auerbach");
h.put(76307, "Karlsbad");

if (h.containsKey(20097))
    System.out.println(h.get(20097));     // Hamburg

System.out.println(h.get(22222));   //  null
System.out.println(h.get(76307));   //  Karlsbad

Set keys = h.keySet(); 
// -> { 20097, 76307 } in unpredictable order.

Collection values = h.values();  
// -> { "Hamburg", "Karlsbad" } in unpredictable order.

Set> entries = h.entrySet();  
// -> { {20097, "Hamburg"},  {76307, "Karlsbad"} }
//    in unpredictable order. 

Properties class

The Properties class is a Map that according to docs shall only contain String-String pairs. Nevertheless, and strange but true: it is derived from Hashtable, not from Hashtable.

The Properties class can be used to store ini-like files on disk. An example on how to use Properties to read and write data follows.

Properties p = new Properties();
p.setProperty("a", "A");
p.setProperty("b", "xy");

static void StoreProperties(String filename, Properties prop)
       throws IOException
{
    FileWriter fw = null;
    try
    {
        fw = new FileWriter(filename);
        prop.store(fw, "This is a comment.");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (fw != null)
            fw.close();  // may throw
    }
}

static void ReadProperties(String filename, Properties prop) 
       throws IOException
{
    prop.clear();
    Reader fr = null;
    try
    {
        fr = new FileReader(filename);
        prop.load(fr);
    }
    catch  (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if( fr != null)
            fr.close();  // may throw
    }
}

Dictionary

From Java 1.0 on, there has been the abstract class Dictionary which of course denotes the same concept as the Map. So you will find this in legacy code frequently. Nowadays, Dictionary is deprecated.

IEnumerable, Equals, Indexers, …

equals, hashCode and compareTo

The Java methods equals, hashCode and compareTo are analog to C#’s Equals, GetHashCode and CompareTo. Like in C#, if you use any of the generic containers you must be aware that these methods must be implemented on your classes. Otherwise strange things will happen.

IEnumerable, IEnumerator / Iterable, Iterator

Iterable is the Java equivalent of C#’s IEnumerable and Iterator is the Java equivalent of IEnumerator. The following two code snippets show their usage.

// Java
TreeSet ts = ...;

Iterable t = ts;
for(java.util.Iterator it = t.iterator(); it.hasNext();)
        System.out.print(it.next() + " "); 

// C# 
List a = ...;

IEnumerable  t = a; 
for(IEnumerator en = t.GetEnumerator(); en.MoveNext();)
    Console.Write(en.Current + " ");

Some further Gotchas:

  • Ordinary Java arrays do not implement IEnumerable. Nevertheless you can iterate over them by the extended for loop.
  • Collections of primitive types are not allowed in Java. You need to use the corresponding wrapper class. Example: List = new LinkedList();
  • Indexers do not exist in Java. Access to elements of array-like collections can be done by get(i) instead.

Java for C# Programmers 9: Reflection

Reflection

Java has full-fledged reflection powers.

    List ll = new LinkedList();

    ll.add(13);
    ll.add('A');
    ll.add(true);
    ll.add(3.14);
    ll.add("Java");

    for(Object o: ll)
        System.out.printf("%s -> %s \n", o, o.getClass());

puts out

13 -> class java.lang.Integer 
A -> class java.lang.Character 
true -> class java.lang.Boolean 
3.14 -> class java.lang.Double 
Java -> class java.lang.String 

is / as / instanceof

The is operator in C# has an equivalent in Java: instanceof.
No equivalent for the as operator does exist in Java. You could use this function as a replacement.

public static  T as(Class c, Object o)
{
    if(c.isInstance(o))
        return c.cast(o);
    return null;
}

Print Class Information Via Reflection

To print all available information about a type you can use the following class ReflectionInfo.

static public class ReflectionInfo
{
    private static Constructor [] constructors;
    private static Field[] fields;
    private static Method[] methods;

    public static void main(String[] args)
    {
        GetInfo("java.lang.String");
        PrintInfo();
    }

    private static void GetInfo(String className)
    {
        try
        {
            // create class object
            Class cl = Class.forName(className); 
            constructors = cl.getConstructors();
            fields = cl.getDeclaredFields();
            methods = cl.getMethods();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static void PrintInfo()
    {
        PrintConstructors();
        PrintFields();
        PrintMethods();
    }

    private static void PrintConstructors()
    {
        System.out.println("\nConstructors");
        for(int i = 0; i < constructors.length; ++i)
            System.out.printf("%02d: %s \n", i+1, constructors[i]);
    }

    private static void PrintFields()
    {
        System.out.println("\nFields");
        for(int i = 0; i < fields.length; ++i)
            System.out.printf("%02d: %s \n", i+1, fields[i]);
    }

    private static void PrintMethods()
    {
        System.out.println("\nMethods");
        for(int i = 0; i < methods.length; ++i)
            System.out.printf("%02d: %s \n", i+1, methods[i]);
    }
}

The code above prints the following.

Constructors
01: public java.lang.String(byte[]) 
02: public java.lang.String(byte[],int,int)

    ... (snip) ...

11: public java.lang.String(java.lang.String) 
12: public java.lang.String() 
13: public java.lang.String(byte[],int,int,java.lang.String) 
            throws java.io.UnsupportedEncodingException 
14: public java.lang.String(byte[],int) 
15: public java.lang.String(byte[],int,int,int) 

Fields
01: private final char[] java.lang.String.value 
02: private int java.lang.String.hash 
03: private static final long java.lang.String.serialVersionUID 
04: private static final java.io.ObjectStreamField[] 
            java.lang.String.serialPersistentFields 
05: public static final java.util.Comparator
            java.lang.String.CASE_INSENSITIVE_ORDER 
06: private static final int java.lang.String.HASHING_SEED 
07: private transient int java.lang.String.hash32 

Methods
01: public boolean java.lang.String.equals(java.lang.Object) 
02: public java.lang.String java.lang.String.toString() 
03: public int java.lang.String.hashCode() 
04: public int java.lang.String.compareTo(java.lang.Object) 
05: public int java.lang.String.compareTo(java.lang.String)

    ... (snip) ...

64: public java.lang.String
                   java.lang.String.toUpperCase(java.util.Locale) 
65: public java.lang.String java.lang.String.toUpperCase() 
66: public java.lang.String java.lang.String.trim() 
67: public final void java.lang.Object.wait(long,int) 
            throws java.lang.InterruptedException 
68: public final native void java.lang.Object.wait(long) 
            throws java.lang.InterruptedException 
69: public final void java.lang.Object.wait() 
            throws java.lang.InterruptedException 
70: public final native java.lang.Class 
            java.lang.Object.getClass() 
71: public final native void java.lang.Object.notify() 
72: public final native void java.lang.Object.notifyAll() 

Calling Constructors And Methods via Reflection

Check this example to see how constructors and methods can be called via reflection.

static public class ReflectionInfo
{
    private static Constructor[] constructors;
    private static Field[] fields;
    private static Method[] methods;

    public static void main(String[] args)
    {
        GetInfo("java.lang.String");
        UseReflectedMethods();
    }

    private static void UseReflectedMethods()
    {
        try
        {
            Constructor cons = null;
            // look for the String(String) constructor
            for (Constructor c : constructors)
            {
                if (c.toString().contains("(java.lang.String)"))
                {
                    cons = c;
                    break;
                }
            }

            // Create a new instance of a String 
            // with a String parameter. 
            String s = (String) cons.newInstance("abcde");
            System.out.println(s);    // -> abcde

            Method met = null;
            // look for the concat method
            for (Method m: methods)
            {
                if (m.toString().contains("concat"))
                {
                    met = m;
                    break;
                }
            }

            // Call a method on String s.
            String t = (String) met.invoke(s, " xyz");
            System.out.println(t);    // -> abcde xyz

        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    private static void GetInfo(String className)
    {
        try
        {
            // create class object
            Class cl = Class.forName(className); 
            constructors = cl.getConstructors();
            fields = cl.getDeclaredFields();
            methods = cl.getMethods();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Java for C# Programmers 8: Applets

Java Applets

A Java applet is a Java program that is usually run in a web browser. The Java bytecode is hosted on a web server and delivered to the user. In the user’s browser, the applet is run by a JVM which is part of the browser, usually in form of a plugin.

There are these main differences to a normal Java app.

  1. The main class must be derived from java.applet.Applet or, for a Swing applet from javax.swing.JApplet.
  2. There is no static void main(..) function. Instead, an applet has several functions that can and should be overridden by your applet. They are explained in the template below.
  3. No size inside the applet. Size is taken from HTML.
  4. An applet is closed, when the browser (or tab) is closed.
  5. An applet can not have a title, only the website can have it.
public class AppletTemplate extends Applet  // or JApplet
{
    // Is called once when the applet is first loaded 
    // into the browser.
    public void init() { }

    // Is called after loading of the applet, whenever the 
    // applet becomes visible. It then should start its execution.
    public void start() { }

    // Is called when the applet becomes invisible, e.g. because some 
    // other window is put in front of the applet. The applet then 
    // should stop its execution.
    public void stop() { }

    // Is called, when the applet is removed from memory. An applet
    // that uses resources must free them here.  
    public void destroy() { }

    // Is called when something shall be painted. 
    public void paint (Graphics g) { }
}

How to Test Your Java Applet Locally

It is easy to test it via Eclipse. When the active window contains an applet and you start debugging, automatically Eclipse’s applet viewer starts and shows the applet.

But at some point, you’ll probably want to see your applet running in a browser.

To be able to view an applet in the browser, a link to the applet has to be put into some html code. You can use the deprecated applet or the newer object tag. An example for both follows. The applet class here is ColorMixerClass in package Applets.


    
        

ColorMixer Java Applets

Gotcha: There are some minutiae which you need to know.

  1. Use a fully qualified URL-like path in the archive parameter, with leading file://. Just giving C:\Data\Java-works\bin\ColorMixer.jar in the example above will lead to an IllegalArgumentException: name.
  2. In the code or classid parameter, give the full path of the applet class inside the jar. Otherwise you’ll get an ClassNotFoundException
  3. Astounding, but true: Some of the latest Java update put a higher security restriction on applets coming from the local file system, than it does for applets from the internet.
    So even if you can run Java applets from the internet in your browser, it is probable that you cannot run the applet that you’ve written yourself and that is located on your local harddrive. If that is the case, you need to lower your computer’s security settings.

    1. Go to your Control Panel/Java/Configure Java/Security and put the security to Medium.
    2. After changing the security level, you might need to end some hanging browser and/or Java processes until you can get your applet to run.