Monday 13 December 2010

CascadeType Explained

PERSIST
maps to EnityManager.persist(). Make an instance managed and persistent.
MERGE
maps to EnityManager.merge(). Merge the state of the given entity into the current persistence context.
REMOVE
maps to EnityManager.remove(). Remove the entity instance.
REFRESH
maps to EnityManager.refresh(). Refresh the state of the instance from the database, overwriting changes made to the entity, if any.
ALL
all of the above

References



Java Persistence with Hibernate
Christian Bauer, Gavin King

Friday 10 December 2010

What is the biggest source of bugs in Software?

Riddle:What is the biggest source of bugs in Software?

Solution: Software Designers

Thursday 9 December 2010

Composite Primary Keys

Besides Java, I do have a lot to do, as do we all, I presume, with Database and Database Administration and Database Design.

In my current job, I see a lot of code where a join table has a single column, an autogenerated id, for a Primary Key. And it's really annoying.

Due to lack of proper unique indexes, there are a lot of duplicate records in the table, only they're not duplicate because they have a unique Primary Key (an autogenerated id).

If the table is a perfect example of a way of joining two tables together, there is no reason not to have a combined Primary Key consisting of the two foreign keys used to join the other two tables together.

Example:

Table:
User
id
Table:
Widget
id

Bad Example:

Join Table:
User_Widget
id
user_id
widget_id

Good Example:

Join Table:
User_Widget
user_id
widget_id

In the good example, the constraints of the Primary Key take care of everything, it's quicker, it's more efficient, and it's always correct.

Friday 3 December 2010

Yahoo Web Best Practices

One of the most enlightening articles I've read in a long time, regarding the responsiveness (and the way to increase it) of websites. http://developer.yahoo.com/performance/rules.html#page-nav

Friday 15 October 2010

Java Tooling

A list of tools I like to use:
  • JBoss Tattletale 1.1
  • JavaMelody
  • Hudson

Pass by Reference or Pass by Value?

The best explanation of how Java deals with

  • Pass By Reference and
  • Pass by Value
I've read in a long time.

http://www.yoda.arachsys.com/java/passing.html

Friday 8 October 2010

Showing your Microsoft SQL JDBC Driver Version

I wanted to find out which Microsoft MS SQL JDBC Driver I was using, without tearing open .jar files and reverse engineering stuff. Here's some Java Reflexion that does what I wanted.
try {
    Class cls = Class.forName("com.microsoft.sqlserver.jdbc.SQLJdbcVersion");
    Field fieldlist[] = cls.getDeclaredFields();
    for (Field fld: fieldlist) 
    {
        fld.setAccessible(true);
        out.append("<tr><td>" + fld.getName() + ":" + fld.getInt(cls)+ 
            "</td></tr>");
    }
}
catch (Throwable e) 
{
    log.error("problem getting sql driver version", e);
}

Thursday 16 September 2010

Extending Hibernate/HQL with Database Proprietary Stuff

http://www.roseindia.net/hibernate/firstexample.shtml http://stackoverflow.com/questions/740293/is-it-possible-to-do-standard-deviation-in-nhibernate

Volatile - A Definition (Warning:Swear words)

I seem to have stumbled upon a definition of volatile at bash.

the compiler goes "oh look, it's checking the same memory location over and over. let's stick it in a hardware register and just use THAT value so it's faster", but volatile says "no way bitch. shit happens to this memory location regardless of what's going on in the program itself. keep checking the actual location or so help me god I will break your face"

Friday 10 September 2010

Strings are immutable

Sometimes I come across something like this:
String myString = "Jack";

// Concatenates the specified string to the end of this string.
// (taken directly from JavaDoc)
myString.concat(" and the Beanstalk");

And people are very surprised when they see that the String myString has not been changed.

It is very confusing, the javadoc helps if you've noticed that a new String is returned by the concat method. Strings cannot be changed! Therefore, either use StringBuffer or be prepared to create a huge pile of new String objects.

Thursday 2 September 2010

Calling JSP directly

Calling a JSP directly, (from for example within another jsp) in order to redirect its input and output to, for example, a PDF writer, can be done using the following:

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * Response wrapper, that creates its own readable buffer.
 * @author Turbo
 */

public class WebResponseWrapper extends HttpServletResponseWrapper 
{
    
    private StringWriter output;

    public WebResponseWrapper (HttpServletResponse response){
    super(response);
    output = new StringWriter();
    }

    public String getBufferContents()
    {
        return output.toString();
    }

    @Override
    public void flushBuffer() throws IOException {
    }
    
    @Override
    public PrintWriter getWriter() throws java.io.IOException
    {
        return new PrintWriter(output, true);
    }

    @Override
    public void reset() 
    {
    }

    @Override
    public void resetBuffer()
    {
    }

}
/**
 * Class that makes it possible to add some parameters to the existing
 * http request, useful for redirecting.
 */
 
class MyRequestHelper extends HttpServletRequestWrapper
{
    Map<String,String> theMap = null;
    
    public void set(String param, String value)
    {
        theMap.put(param, value);
    }
    
    public MyRequestHelper(HttpServletRequest request)                
    {
        super(request);
        theMap = new HashMap<String,String>();
    }
    
    @Override
    public String getParameter(String param)
    {
        if (theMap.containsKey(param))
        {
            return theMap.get(param);
        }
        return super.getParameter(param);
    }
}

Using these two classes, redirecting a jsp page becomes as simple as:

/* setup wrappers */
WebResponseWrapper resWrapper = new WebResponseWrapper(response);
RequestDispatcher rd = context.getRequestDispatcher("/some/jsp/thing/myJsp.jsp");
MyRequestHelper mrh = new MyRequestHelper(request);

/* change/add some parameters */
mrh.set("forEmail""true");
mrh.set("key", correctKey);
mrh.set("user", userName);

/* issue include to the requestdispatcher */
rd.include(mrh, resWrapper);

/* retrieve output */
String email = resWrapper.getBufferContents();

NullPointerException - Most Common Java Bug In Existence

Unless you are what is called "the Perfect Java Programmer", it is likely that you've perpetrated the NullPointerException at least once (and probably a lot more) in your life.

A lot of the time, I see code like the following:
if (propertyValue.equals("filename.txt"))
{
    // do stuff
}
When it should really be more like this:
if ("filename.txt".equals(propertyValue))
{
    // do stuff
}

Now, as you can see when you try this (with propertyValue = null;), a NullPointerException does not take place.

The reason is in the equals method. Contract states that x.equals(null) == false.

If you're new at Java, you might be rather surprised that something like "somestring".equals() works. Remember that Strings are immutable objects, and therefore there's really no reason not to try something like this.

With that said, let's try and find a common implementation for the equals method. Eclipse seems to do a pretty good job of it:

public class MyObject
{

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            // it is the same object
            return true;
        }
        if (obj == null)
        {
            // oh dear
            return false;
        }
        if (getClass() != obj.getClass())
        {
            // not the same class
            return false;
        }
        MyObject other = (myObject) obj;
        if (!this.field().equals(obj.field())
        {
            // (one of) the fields is not the same!
            return false;
        }
        // couldn't find any differences!
        return true;
    }

    @Override
    public int hashCode() 
    {
        return field();
    }

}
The link to http://community.jboss.org/wiki/EqualsandHashCode might be a good one.

Tuesday 17 August 2010

Different JSON formats

Found the following examples of different JSON formats here.
@XmlRootElement

public static class SimpleJaxbBean 
{

   public String name = "Franz";

   public String surname = "Kafka";

}
XML output:
<simpleJaxbBean>
  <name>Franz</name>
  <surname>Kafka</surname>
</simpleJaxbBean>
Badgerfish format:
{"simpleJaxbBean":{"name":{"$":"Franz"},
"surname":{"$":"Kafka"}}}
Mapped format (Jettison):
{"simpleJaxbBean":{"name":"Franz",
"surname":"Kafka"}}
and finally Jersey default format:
{"name":"Franz",
"surname":"Kafka"}

Monday 16 August 2010

Installing And Configuring Glassfish on Linux

Installing and configuratin of Glassfish is fairly straightforward if you have some kind of package manager. And who hasn't nowadays?

However, after that the following points come forward:
  • put the logging in /glassfishv3/glassfish/domains/domain1/config/logging.properties in the proper sequence (most detailed first) otherwise, a previous entry may remove the settings of a more specific next entry.

Wednesday 4 August 2010

When to use redirect en when to use forward

This is just to remind me.

These are the two and the differences:

  • response.sendRedirect("http://www.xyz.com")

    • send a redirect request back to the browser
    • is slow
    • will change the location
  • pageContext.forward("http://www.xyz.com") and requestDispatcher.forward("http://www.xyz.com")

    • sends a forward request right onto the next page/jsp
    • is faster
    • will not change the location
    • you still have access to the original request
  • pageContext.include("http://www.xyz.com") and requestDispatcher.include("http://www.xyz.com")

    • includes a request into the current page/jsp
    • will not change the location
    • you still have access to the original request
    • you can continue processing when you get back control
    • good for including content from another page

Tuesday 27 July 2010

The Terrible Dangers of Autoboxing (Part 2)

Solution to part 1:
j is equal to m
j is equal to K
K is equal to m

The result of one of the Object being null, will of course cause a NullPointerException.

Part 2:

class Autoboxing


    public static void main(String[] args)
    {
        Integer a = 10;
        Integer b = 10;
        Integer c = 1000;
        Integer d = 1000;
        System.out.println(a == b); //true
        System.out.println(c == d); //false
    }

};

Please explain.

(Found it in my Linkedin groups "Sun Certified Java Programmer" here)


References

Most common gotchas in Java
http://vanillajava.blogspot.nl/2014/02/most-common-gotchas-in-java.html

Monday 26 July 2010

The Cycle

Somewhere during the lifetime of a software development project, especially when concerning frameworks, the following things happen:

  1. a software project is started
  2. people notice that it is convenient and easy to use
  3. people demand new changes, and additional functionality
  4. the small software project starts to grow into the form of a framework
  5. the small software project becomes big, unruly, difficult to use, slow, hard to maintain, has all sorts of functionality that most people do not need.
  6. some people grow tired/irritated at the state of things
  7. some people have the great idea to make something better...

Somewhere,... a software project is started.

Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: <Object.value>, no session or session was closed

ERROR [STDERR] Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: <Object.value>, no session or session was closed

Sooner or later, anyone using Hibernate, is running into this problem.

Check out http://community.jboss.org/wiki/OpenSessioninView

Sunday 25 July 2010

REST Webservice URI setup

Thank heavens I found the blog topic http://marxsoftware.blogspot.com/2010/02/jax-rs-with-jersey-introduction.html.

So, here's the setup.

http://hostname/<context root of web application>/<url pattern of the servlet mapping>/<path defined in java class>

http://
hypertext transfer protocol
hostname
the hostname where the web server is lurking
context root of web application
the context root is defined by the proprietary xml file sun-web.xml
url pattern of the servlet mapping
the url pattern defined in the web.xml for a particular servlet, to indicate for which urls the servlet needs to be called
path defined in java class
the path is defined in the java class that is going to function as the REST webservice. It's defined by means of the @Path annotation on the Class itself.

Wednesday 14 July 2010

Scaling large amounts of images in a directory structure

The following links helped me a lot!
import java.util.*;
import java.io.*;

import java.awt.image.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.io.FilenameFilter;

public class Autoboxing
{
    public static String DESTINATION_PATH = "C:\\destination";

    public static String SOURCE_PATH = "C:\\source";

    public static boolean verbose = false;

    public static int MAX_RETRIES = 20;
   
    /**
     * Saves a BufferedImage to the given file, pathname must not have any
     * periods "." in it except for the one before the format, i.e. C:/images/fooimage.png
     * @param img
     * @param ref a pathname
     */

    public static void saveImage(BufferedImage img, String ref)
    {
        try {
            String format = (ref.endsWith(".png")) ? "png" : "jpg";
            ImageIO.write(img, format, new File(ref));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage loadImage(File ref)
    {
        BufferedImage bimg = null;
        try {

            bimg = ImageIO.read(ref);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bimg;
    }

    /**
     * Convenience method that returns a scaled instance of the
     * provided {@code BufferedImage}.
     *
     * @param img the original image to be scaled
     * @param targetWidth the desired width of the scaled instance,
     *    in pixels
     * @param targetHeight the desired height of the scaled instance,
     *    in pixels
     * @param hint one of the rendering hints that corresponds to
     *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
     *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
     *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
     *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
     * @param higherQuality if true, this method will use a multi-step
     *    scaling technique that provides higher quality than the usual
     *    one-step technique (only useful in downscaling cases, where
     *    {@code targetWidth} or {@code targetHeight} is
     *    smaller than the original dimensions, and generally only when
     *    the {@code BILINEAR} hint is specified)
     * @return a scaled version of the original {@code BufferedImage}
     */

    public static BufferedImage getScaledInstance(BufferedImage img,
                                           int targetWidth,
                                           int targetHeight,
                                           Object hint,
                                           boolean higherQuality)
    {
        int type = (img.getTransparency() == Transparency.OPAQUE) ?
            BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage ret = (BufferedImage)img;
        int w, h;
        if (higherQuality) {
            // Use multi-step technique: start with original size, then
            // scale down in multiple passes with drawImage()
            // until the target size is reached
            w = img.getWidth();
            h = img.getHeight();
        } else {
            // Use one-step technique: scale directly from original
            // size to target size with a single drawImage() call
            w = targetWidth;
            h = targetHeight;
        }
    int count = 0;
        do {
        count ++;
            if (count > MAX_RETRIES)
            {
                throw new RuntimeException("Max retries reached.");
            }
            if (higherQuality && w > targetWidth) {
                w /= 2;
                if (w < targetWidth) {
                    w = targetWidth;
                }
            }

            if (higherQuality && h > targetHeight) {
                h /= 2;
                if (h < targetHeight) {
                    h = targetHeight;
                }
            }

            BufferedImage tmp = new BufferedImage(w, h, type);
            Graphics2D g2 = tmp.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
            g2.drawImage(ret, 0, 0, w, h, null);
            g2.dispose();

            ret = tmp;
        } while (w != targetWidth || h != targetHeight);

        return ret;
    }

    /**
     * Recursively resizes images.
     * @param directory the source directory containing .jpg files
     * @param destination the destination directory where the resized .jpg files are to be put
     * @param filter the filter to use, for example *.jpg
     * @param recurse wether or not to traverse the directory tree
     * @param recreate wether or not to recreate the entire directory tree
     * in the destination or simply dump .jpg files.
     * @param overwrite true, it overwrites existing files, false, if destination file already exists, skips it.
     */

    public static void changeFiles(
            File directory,
            File destination,
            FilenameFilter filter,
            boolean recurse,
            boolean recreate,
            boolean overwrite)
    throws IOException
    {
        if (verbose) System.out.println("Checking directory : " + directory.getCanonicalPath() + " with " + destination.getCanonicalPath() );
        // List of files / directories
        Vector<File> files = new Vector<File>();
       
        // Get files / directories in the directory
        File[] entries = directory.listFiles();
       
        // Go over entries
        for (File entry : entries)
        {
            if (verbose) System.out.println(" File: " + entry.getName());
            // If there is no filter or the filter accepts the 
            // file / directory, resize the image found
            if (filter == null || filter.accept(directory, entry.getName()))
            {
                File newFile = new File(destination.getCanonicalPath() + File.separator + entry.getName());
                if (newFile.exists() && !overwrite)
                {
                    // skipping this one, already done apparently.
                    if (verbose) System.out.println(" File " + newFile .getCanonicalPath() + " exists, skipped.");
                    continue;
                }

                try
                {
                    BufferedImage theImage = loadImage(entry);
                    theImage = getScaledInstance(theImage, 50, 50,  RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
                    if (!recreate)
                    {
                        saveImage(theImage, destination.getCanonicalPath() + "\\" + entry.getName());
                    }
                    else
                    {
                        if (!newFile.exists())
                        {
                            // create the equivalent
                            newFile.createNewFile();
                        }
                        saveImage(theImage, newFile.getCanonicalPath());
                    }
                }
                catch (Exception e)
                {
                    System.out.println("Error resizing image " + entry.getCanonicalPath());
                    e.printStackTrace();
                }
            }
           
            // If the file is a directory and the recurse flag
            // is set, recurse into the directory
            if (recurse && entry.isDirectory())
            {
                if (recreate)
                {
                    File newFile = new File(destination.getCanonicalPath() + File.separator + entry.getName());
                    if (!newFile.exists())
                    {
                        // create the equivalent
                        newFile.mkdir();
                    }
                    changeFiles(entry, new File(destination.getCanonicalPath() + File.separator + entry.getName()), filter, recurse, recreate, overwrite);
                }
                else
                {
                    changeFiles(entry, new File(destination.getCanonicalPath()), filter, recurse, recreate, overwrite);
                }
            }
        }

    }

    public static class MyFilenameFilter implements FilenameFilter
    {
        public boolean accept(File dir,
                        String name)
        {
            return name.endsWith(".jpg");
        }
    }
   
   
    public static void main(String args[])
    throws IOException
    {
        boolean overwrite = false;
        boolean recursive = false;
        boolean recreate = false;
        boolean nextIsDestination = false;
        boolean nextIsSource = false;
        String destination = DESTINATION_PATH;
        String source = SOURCE_PATH;
        for (String argument : args)
        {
            if (nextIsDestination)
            {
                destination = argument;
                nextIsDestination = false;
            }
            if (nextIsSource)
            {
                source = argument;
                nextIsSource = false;
            }
            if ("-r".equals(argument))
            {
                recursive = true;
            }
            if ("-tree".equals(argument))
            {
                recreate = true;
            }
            if ("-s".equals(argument))
            {
                nextIsSource = true;
            }
            if ("-d".equals(argument))
            {
                nextIsDestination = true;
            }
            if ("-o".equals(argument))
            {
                overwrite = true;
            }
            if ("-v".equals(argument))
            {
                verbose = true;
            }
        }
       
        File src_file = new File(source);
        File dest_file = new File(destination);
        System.out.println("absolute path: " +  src_file.getAbsolutePath());
        System.out.println("canonical path: " +  src_file.getCanonicalPath());
        System.out.println("path: " +  src_file.getPath());
        System.out.println("name: " +  src_file.getName());
        changeFiles(src_file, dest_file, new MyFilenameFilter(), recursive, recreate, overwrite);
    }
}

Friday 9 July 2010

Concurrency problems in jsp Pages

I'm so ashamed that I didn't notice this problem sooner, but apparently servlets (and, therefore, jsp pages too) are instanced and put into a pool for multithreaded use.

This has the very bad effect of messing with your class variables.

So, do NOT do the following:

<%!
// authentication && authorization

/* name of the current user logged in */
private String itsPlayerName;

private Logger itsLog = Logger.getLogger("mmud");
 
/* password of the current user logged in, unsure if used */
private String itsPlayerPassword = "";
 
/* sessionid/cookiepassword of current user */
private String itsPlayerSessionId;

private StringBuffer contents = new StringBuffer("");
%>

A JSP page is by default thread unsafe. This means that multiple requests, started in multiple threads for a specific JSP access the same Instance.

Do not make your JSP page threadSafe="true". It will become a performance nightmare.

If you are interested, the following is put in the javadoc of the javax.servlet.Servlet interface service method:

Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet's class and instance variables.

How to Transmit New Objects To REST Service

One of the reasons for adding this, is because there was a huge lack of POST/PUT/DELETE/HEAD examples out there, and I thought I should do my part. Although the principles are the same as with GET.

I've been at it for some time now, and for some reason there always seem to be one or two things that go wrong when creating a new REST Service, even though I've created a working REST Service not two days ago. That in itself is kind of frustrating.

Check out Japod's Blog for starters. In order to use more complicated Data Structures in REST, these need to be defined in a derivative of the JAXBContext class.

Personally, I really don't understand why that same cannot be done using simple Annotations, but that's just me.

Then there's the security issue. How to see who the person is that is accessing the webservice. Luckily, I found me some help here.

There seems to be some confusion regarding the mapping of the HTTP calls3, which I've tried to put in the picture above.

Updated 14/09/2014.

References

[1] Why PUT and DELETE?
http://www.artima.com/lejava/articles/why_put_and_delete.html
[2] rfc2616
http://www.ietf.org/rfc/rfc2616.txt
[3] Wikipedia - Representational state transfer
http://en.wikipedia.org/wiki/Representational_state_transfer#Architectural_constraints

Friday 25 June 2010

Displaying the Date

I always always get in trouble when using Date, because of the huge number of deprecated methods it has. We should use Calendar almost exclusively.

Here's a simple example of a bad way and a good way to display a nice date:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DisplayDate
{

    public static void main(String args[]) 
    {
        // worse way
        Date myDate = new Date();
        int month = myDate.getMonth();
        int year = myDate.getYear();
        int day = myDate.getDate();
        System.out.println("Current date : " +
            day + "/" + (month + 1) + "/"
            + (year + 1900));
        Calendar cal = Calendar.getInstance();

        // bad way
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println("Current date : " +
            day + "/" + (month + 1) + "/" + year);

        // good way
        SimpleDateFormat simpleDateFormat = 
            new SimpleDateFormat("dd/MM/yyyy");
        String s =
           simpleDateFormat.format(cal.getTime());
        System.out.println("Current date : " + s);

    }
}

References

Javadoc - SimpleDateFormat
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Wednesday 23 June 2010

JSON and the single-value array

The one you really need to read can be found here : https://blogs.oracle.com/japod/entry/configuring_json_for_restful_web

Jersey NATURAL JSON notation is awesome.

28-05-2012: Updated with new links to more up to date content.

Monday 21 June 2010

Getting your Windows Process Id

A java-unrelated post for once. I've been having huge issues with the fact that all my java programs running on my windows machine all have the command line "java.exe", which is no surprise. But how to decide which one (that's run out of memory or otherwise hangs) to shut down?

I needed the process id.

Thank god for http://www.scheibli.com/projects/getpids/index.html.

Tuesday 11 May 2010

ConcurrentModificationException occurred

Recently had a ConcurrentModificationException in a single threaded piece of code. That was weird. Luckily there are lots of resources (google is your friend) that tell you how to solve it.

Here's the offending piece of code.

Set<Orders> ordersToDelete = customer.getOrders();
        
for(Order order : ordersToDelete)
{
    order.setCustomer(null);
    customer.getOrders().remove(order);
    order.setCompany(null);
    genericCustomDAO.remove(order);
}
I thought about just "nulling" the Set in Customer, but that is not possible as hibernate wants to have references removed before attempting to remove the object itself. (yeah, I should look into the whole CascaseType.ALL thing sometime.)

The ugliest thing that you could do is of course make a copy of the set and then iterate over this new set, removing the items in the old set.

Now, if we only had access to the nice Iterator that the foreach loop above uses, things would be fine. But we do not, so it is time to grasp back to the ancient days where we had to write our own for-loops.

Iterator<Order> ordersToDelete = 
    customer.getOrders().iterator();
        
while (ordersToDelete.hasNext())
{
    Order order = ordersToDelete.next();
    order.setCustomer(null);
    // remove the item from the set by using the
    // remove method of the iterator
    order.setMeasure(null);
    ordersToDelete.remove();
    genericCustomDAO.remove(order);
}
Calling the remove on the iterator itself solves the problem for me.

Tuesday 2 March 2010

The Terrible Dangers of Autoboxing (Part 1)

Below piece of code indicates why some manner of caution is called for when using ints and Integers interchangeably.

Can you tell what the code will do?

Can you tell what happens when Integer K = null?

public class Autoboxing
{

    public static void main(String [] testAutobox)
    {
        int j = 5;
        Integer K = new Integer(5);
        Integer L = new Integer(5);
        int m = 5;
        if (j == m)
        {
            System.out.println("j is equal to m");
        }
        if (j == K)
        {
            System.out.println("j is equal to K");
        }
        if (K == L)
        {
            System.out.println("K is equal to M");
        }
        if (K == m)
        {
            System.out.println("K is equal to m");
        }
    }

}
Addendum: Recently I got a weird problem when I was debugging in Eclipse. Apparently autoboxing doesn't work very well when trying to use expressions to evaluate in the Debugger. Perhaps Autoboxing, in this case, doesn't work, and the two objects are compared based on their memory address as is the default behaviour.

References

Most common gotchas in Java
http://vanillajava.blogspot.nl/2014/02/most-common-gotchas-in-java.html

Friday 26 February 2010

Trying out some code formatting.

import java.util.List;

public class MyObject
{
    /**
     * Stuff
     * @author Turbo
     */

    public void doStuff() 
    {
        // should be some stuff here.
        System.out.println("Hello, world!");
    }

}

Code formatter was found right here.

Wednesday 24 February 2010

My First Attempt At A Blog

I've decided to try my hand and this 'blog' thing. Right now it's just a way for me to write down some of my thoughts on some of the things that bother me on the current state of Software Design with Java and JEE and basically everything that's circling around it.

public class HelloWorld 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello, world!");
    }
}