# 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();
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;
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

``````

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

// 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));
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();
``````

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
``````

# 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");

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

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

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();
try
{
}
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.

# Reflection

Java has full-fledged reflection powers.

``````    List ll = new LinkedList();

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();
}
}
}

Posted in Java

|

Tagged C#, Java

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.

The main class must be derived from java.applet.Applet or, for a Swing applet from javax.swing.JApplet.
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.
No size inside the applet. Size is taken from HTML.
An applet is closed, when the browser (or tab) is closed.
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() { }

// 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.

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.
In the code or classid parameter, give the full path of the applet class inside the jar. Otherwise you’ll get an ClassNotFoundException
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.

Go to your Control Panel/Java/Configure Java/Security and put the security to Medium.
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.

Posted in Java

|

Tagged Applet, C#, Java

Java for C# Programmers 7: Binaries

Source Code and Binaries Organization
Source Code

Every source code file must contain maximally one public class. There may be more than one non-public classes.
The name of the public class – if there is any – must be identical to the first part of the source code file.
Source code file:  MyLove.java -> public class MyLove
Partial classes are not allowed.

Binaries

From MyLove.java a MyLove.class is created. The .class file contains the Java bytecode of the associated .java file.
From  .class files and ressources a XYZ.jar (Java ARchive) can be created. A jar file is mainly a zip file of its contents, maybe with an added metadata file and the file extension .jar instead of .zip.
In principle, a jar file is something similar to an assembly or dll in .NET. The term jar hell is well known to Java developers.
A jar file can be a runnable jar file or a library.
The jar commandline program can be used to create or inspect jar files. It is a zip program with tar like syntax.
jar tvf XYZ.jar shows a verbose content listing of XYZ.jar.
In Eclipse, use File - Export - Java to create a jar file.

Runnable Jar Files

A runnable jar file is a an ordinary jar file with an added manifest file which contains an entry for the main class.
The main class must have a public static void main(String[] args) method. This method will be called when the jar is run.
The manifest file is an ordinary UTF-8 encoded text file called MANIFEST.MF located in the folder META-INF. It can contain information about signing, version control, package sealing and others.

An entry for a main class may look like this
Main-Class: Gaming.TraceOfDeathEngine

Here, Gaming is the package name and TraceOfDeathEngine is the class name.
Create a Runnable Jar, V1

This method will pack all the files of the project into the jar file. There is no way here to select which files shall be included in the jar and which shall not. But as a jar file is an ordinary zip, you can remove superfluous files afterwards. Or see method 2.
In Eclipse use File - Export - Java - Runnable JAR file to create an executable jar file.
On the the following page, select your main class under Launch configuration and input the file path of the jar file that shall be created.

Create a Runnable Jar, V2

This method will pack only selected files of the project into the jar file.
In Eclipse in the Package Explorer select the project or package which contains most of the stuff that shall be included in the jar.
Use File - Export - Java - JAR file. (Do not select Runnable JAR here. You can create a runnable jar anyway.)
On the the following page, select the Java- and resource files you want to have in the jar. Also set the export destination.
On the fourth page, select Generate the manifest file at the top and at the bottom select your Main class.

Create a Runnable Jar, V3
If you don’t use Eclipse or want to automate creating a runnable jar file, you can use the jar utility.
An example:
jar -cvfe troz.jar  Gaming.TrodEngine Gaming

The command line above explained:
c: create new jar file
v: be verbose
f: specify archive file name
e: pass entry point, create manifest automatically
troz.jar:          the archive file name
Gaming.TrodEngine: the entry point is class `TrodEngine`
in package `Gaming`
Gaming:            the folder to include in the jar.

If you have already a created manifest you can pass it to the jar utility with the m option. Jar will then add it to the jar file as META-INF/MANIFEST.MF
jar cvfm trox.jar  mf.txt Gaming

As said, the jar utility program has tar like syntax. So the line above means:
c: create new jar file
v: be verbose
f: specify archive file name
m: include manifest file
trox.jar: the archive file name
mf.txt:   the manifest file name
Gaming:   the folder to include in the jar.

Some quirks of the jar utility:

The archive file  and the manifest file (or the entrys point) must be specified in the same order as the f , m and  e flags.
If any “file” is a directory then it is processed recursively.
It is not allowed to split the options up. tar cvf trox.jar  m MAN Gaming is not possible.

Start a Java Program On Windows
On Windows, when Java is installed properly, you can doubleclick a runnable jar file from Windows Explorer to start it. Or you can create a shortcut and place it onto the desktop and use the shortcut to start the java program. You cannot attach such a shortcut to the taskbar, though.
To start a runnable abc.jar via commandline and pass parameters param1 and param2 to the main classes main method, just call
java.exe -jar abc.jar param1 param2

You can also start a Java program if you don’t have a jar file, but only the needed .class files. To do this Java.exe must be called from the bin directory one level above the package name.  When the class to start is called MyLove and resides in the package Xcv and the parameters param1 and param2 shall be passed, the command line shall look like this:
java.exe Xcv.MyLove param1 param2

Create a Windows .exe File
To create an executable Windows exe file, you can use launch4j. More details about launch4j are given there (scroll down to method 3 of 3): http://www.wikihow.com/Create-an-Executable-File-from-Eclipse
There are several other possibilities to create a Windows .exe file, namely using Java Web Start technology or an Ahead Of Time compiler or …
A good overview about the available technologies is given here:
http://www.excelsior-usa.com/articles/java-to-exe.html
Libraries
Jar files may be used as libraries and there are zillions of publicly available jar libraries.
This example shows you how to add a MySQL connector library to your Java project.

Extract the package and copy just the mysql-connector*.jar file to somwhere below your workspace. I’d recommend a directory called lib which is a sibling of your bin directory.
In Eclipse, add the jar file to your lib path via Project - Properties - Java Build Path - Libraries - Add External Jars...
This will add the library to your project. Afterwards, you’ll see the library in the Package Explorer under Referenced Libraries.

Posted in Java

|

Tagged C#, Java

← Older posts

Most Popular
Personal Kanban And Kanbanpad: Two Top Productivity Tools
Why Password Managers Aren’t Safe – And Won’t Ever Be
Notepad++: Function List for Tcl and Bash
Why Zip is Better Than 7z

Meta

Entries feed

WordPress.org

Recent Posts

Bee Stings <%\$, <%@, <%=, <%#

ChartDirector Markup Language CDML

Curve Fitting

Many Faces of Tclkits

FFmpeg – Batch Rotate Videos by Commandline Tool

Tags
.NET Library FTP
7-zip
7z
Applet
ASP.NET
Awk
Bash
Book
Browser
C#
Coding
Color
Crashdump
Cygwin
Debugging
Everybody
Fiddler
File Management
FTP
HTML
Image
Java
Kanban
Linux
Pdf
Philosophy
Png
Process
Publishing
Regex
Russinovich
Security
Speed Test
SQLite
SQL Server
Svg
Tcl
Time Management
Tool
Unicode
Unit Tests
Visual Studio
Zip

Recent CommentsUlla on ImpressumHow to Move Thunderbird to Another Computer | 99 Developer Tools on How to Move Firefox to Another ComputerAll You Need is Love | 99 Developer Tools on Visual Studio 2013 for FreeFour Most Essential Firefox Add-Ons And Settings. Plus Seven Extras. | 99 Developer Tools on LeechBlock is a Junkie’s Cure From HeavenAndreas J. Wicker on Zoomit