Posts tagged with "programming"


Theory behind linked lists

Chain photo by Toni Lozano on Wikipedia

One of the things I've had to relearn in Java after not touching it for a while in a university setting is not the concept of linked lists specifically, but how they're implemented. Despite Java having native support for them in its API, we're expected to create our own Linked List objects to use in our programs, presumably to demonstrate we understand the concept and so we could create a really long linked list of grilled cheese sandwiches.

As I understand it in an abstract sense, each node in a linked list contains an object and a pointer to the next node if applicable. The header points to the first node, and the last node points to null. To load in all the nodes we'd traverse the linked lists starting at the head until we encountered a null.

In a similar way to a primitive array with shifting, a linked list is expected to be able to have nodes removed and added from any arbitrary position including at the head and the end.

Adding nodes to a link list

Adding nodes entails traversing the linked list until we come to the node just before where we want to insert our new node. We then point the previous node to our new one, and our new node to the next in.

To add the node to the beginning, we don't need to traverse the list, we just point the header to the new node, and our new node to the previously first node.

To add the node to the end, we traverse until we reach a null value, then have the last node point to our new node, and our new node point to null instead.

Removing nodes

Not surprisingly, removing nodes entails the opposite of adding them. Instead of severing links to place a new node, we sever the nodes between the node to remove and the nodes surrounding it, then link the surrounding nodes. If your programming language doesn't have garbage collection, you'll then want to undefine the object.

If the node is at the beginning we link the header to the next node on the list, and if the node is at the end we take the second last node and point it to null.

Observations

Linked lists (and binary trees etc) are a classic example of a concept which seems perfectly simple when you explain it, but I imagine if you don't plan it and understand it properly you could make a huge mess of it when it comes down to coding. Like deciding to make a grilled cheese sandwich with pop tarts and chocolate ice cream instead seems like a great idea in theory, but you end up setting your toaster oven on fire.


Logos and Java classes for Java classes

Classic Java logo

Despite studying it again for several weeks, every time I see I have a Java "Class" on my timetable I chuckle a bit. If you haven't ever done Java or other object oriented programming before, Java is made up of classes, therefore the whole glorious thing is a delicious pun. Feel free to laugh.

Tee hee, Java classes.

On a slightly related note, who here thinks the old, impressionist Java logo that I've included here was better than their new stylised one? I can't be the only one. Or perhaps I don't want to know.


Using RandomAccessFile objects in Java

Coffee? Java? I know, it's cliche!

Messing around with some basic data files here using RandomAccessFile instead of reading in and writing data files sequentially.

import java.io.*;

public class TestRandomAccess {
  public static void main(String[] args) {
    try {
      RandomAccessFile raf = new RandomAccessFile("raf","rw");
      raf.writeInt(127);
      raf.writeDouble(2.718281828459045);
      raf.writeChars("Bird Bird Bird, the Bird is the Word");
      System.out.println(raf.length());
      raf.seek(4);
      System.out.println(raf.readDouble());
      System.out.println(raf.getFilePointer());
    }
    catch (Exception e) { System.err.println(e); }
  }
}

What's really cool is exporting a seemingly innocuous double (double length floating point number in Java) then reading back as an integer!

import java.io.*;

public class TestRandomAccess {
  public static void main(String[] args) {
    try {
      RandomAccessFile raf = new RandomAccessFile("raf","rw");
      raf.writeDouble(10.0);
      System.out.println(raf.readInt());
    }
    catch (Exception e) { System.err.println(e); }
  }
}

The result: 1076101120. Spiffy!


#SongsInCode

Rick James Super Freak

As if I needed one, but another reason why I love Twitter is the spontaneous memes with a half life shorter than the time it takes for the fizz in soft drink to dissipate when the bottle is opened. I prefer Solo. Well this paragraph rapidly degenerated into nonsense more quickly than most.

Today's fun was coming up with expressing famous songs as code with the surprisingly descriptive #SongsInCode hashtag. @NickHodge by far had the best ones, but I tried my hand at a few too. I spaced them out to make them easier to read, but all these fitted into the 140 character Twitter limit when written on the one line!

if (destination == "San Francisco") {
   hair.wear(flowers);
}
4.times do
   puts "My"
end
puts "Sharona"
if ( headlight >= 1 ) {
   [driveTo : home];
}
%signs = ( "Wild", "Can't Take Home to Mum", "Kinky" );
if ( exists $signs{$girl} ) {
   print "That girl's a super freak!\n"
}
int Mambo = 5;
if ( yourself.takenLookAt() ) {
   me.accuse(allow);
}
for ( my $i = 1; $i < 13; $i++ ) {
   if ($i % 4 == 0) {
      print "$i o'clock rock!";
   } else {
      print "$i o'clock";
   }
}
try {
   makeMeGo("rehab");
} catch(WinehouseRefusalException e) {
   System.out.println("no no no!");
}
Word thing = "Bird";
System.out.println ("The " + thing + " is the "
   + thing.getClass().getName() );

While all those were fun, I think the last was my crowning achievement :).


Choosing a Java IDE

Editing in TextMate

Some people seem to have an almost religious attachment to their text editors of choice, I need not give examples. I tend to gravitate between Vim and MacVim for hacking together single files and TextMate for projects, so when I started doing Java at university again I just fired up the Java bundle in TextMate and off I went.

Back when I was a C++ guy on Windows in early high school I used Visual Studio 6 and later C# in their .NET IDE, but since then I've eschewed IDEs in general because I feel as though they take too much control over what I'm doing, they're complicated and they keep wanting to insert their own code into my files which drives me crazy!

When I started uni and before my major family meltdown back in 2005 I was told to use jGRASP for Java and later Eclipse and NetBeans and I have to admit I decided to go back to a basic text editor (nano at the time), but having just downloaded NetBeans 6.7.1 it seems to have changed a lot in a few short years! The interface is much more Mac-like and it feels nowhere near as sluggish as it did before. I'm still control-freaky enough to want to start my projects from scratch with absolutely nothing (and TextMate is brilliant for this) but there's something to be said for an IDE dedicated to the language you're using.

If you're a Java developer on Mac what editor or IDE do you use to create your poetic scientific whatnot?


Custom Java exceptions

Well today in Java we learnt how to throw our own exceptions. Because Exception is an inherited object of Throwable rather than just a primitive or a pointer we can create our own Exception objects for circumstances where we want Java to treat an event in the same way as an error.

public class TrekError extends Throwable {
  public TrekError() {
    // pass to superclass (Throwable) constructor
    super("Your logic is fatally flawed!");
  }
}
public class TestTrekError {
  public static void main(String[] args) throws TrekError {
    boolean trekBetterThanWars = true;
    if (trekBetterThanWars == false) {
      throw new TrekError();
    } else {
      System.out.println("Live long and prosper!");
    }
  }
}

As I think back to programs I've written in the past in other languages this could have been quite useful! Do Ruby and Python offer similar capability?

The main question I had that I didn't have time to ask in the lecture though was what the "better" or more correct way to use this in Java is. Are there circumstances where you could use such a technique but it would be a cheap shortcut rather than writing robust code? I suspect for all the usefullness that could be derived from this, it could also be easily abused.


Java multiple interface ambiguity

I've been told in lectures that the reason why Java doesn't support multiple inheritance is because every class inherits from the Object class which negates the need for it (perhaps), and because it prevents problems encountered in languages like C++ where multiple parent classes might have methods and data members with the same signatures and names.

What Java does support though is multiple interfaces which lends objects consistent behaviour even if they're completely different:

public class Bicycle implements PeddlePower, Purchasable {
   // I want to ride my bicycle,
   // I want to ride my bike...
}

public class Keyboard implements Purchasable {
   // Bucking spring keyboards are the shiz
}

What I wanted to know is whether or not different interfaces with the same abstract methods and data members could cause a similar clash to the ones avoided by not having multiple inheritance, or whether it would cause an override.

public interface InterfaceA { final int x = 4; }

public interface InterfaceB { final int x = 4; }

public class Testing implements InterfaceA, InterfaceB {
   public class Testing {
      System.out.println(x);
   }
}

Turns out it does generate an error, and now that I've seen it, it does make sense.

Testing.java:5: reference to x is ambiguous, \
both variable x in A and variable x in B match

My reasoning was: imagine you're passing the Testing object to a setter method that accepts any object that implements InterfaceA. I assumed it would know to use the int x data member from InterfaceA and NOT from InterfaceB right? Well of course not, just because it's been passed through something that only accepts objects that implement InterfaceA, that doesn't mean it's lost it's InterfaceB!

Anyway to seasoned Java folk this probably all seems childish and silly, but I find if I try to explain a logic problem out loud to somebody, often I learn the answer myself in the process; in this case why two interfaces can't have methods and data members with the same signatures and names after all! Well technically they could provided you're sure both interfaces will never be used on the same objects at the same time.


When NOT to use Java's array.length method!

Starbucks cups

I know it's cliche using my coffee cup photo here because I'm talking about Java, but I hate blog posts without at least one picture you must understand. Thank you.

A few days ago I posted a beginners problem I was having with Java related to counting how many elements there are in an array; seems basic right?

Here's an example of what I was doing:

for (count = 0; count < arrayThing.length; count++) {
   grandTotal += arrayThing[count].getAmount;
}

As Mark so graciously pointed out for me, I was guilty of a logic error by incorrectly using the length method to determine how many elements there were in the array. The length method returns the entire length of the array that was previously instantiated, NOT up until the index where there have stopped being values entered!

A way to get around this is to use a counter whenever you add a new item to array in a similar fashion to below, then using the counter in place of the length method whenever you need to loop through the values.

public void addToArray(int e) {
   this.arrayThing[nArrayThing] = e;
   nArrayThing++;
}

I was under the impression Java's for each statement could also have been used, but that's for use in collections not arrays.

Thanks to Mark for helping with my rusty Java knowledge :).


My pledge in response to Experts-Exchange

Isn't it great when you realise someone else shares one of your annoyances about something? I can't quite explain why, perhaps it's because in my case it makes me feel less naggy if I know I'm not the only one.

Andrew Barnett made a wish on Twitter this afternoon that upon reading it I jumped up on my chair, shouted "YES!" then fell off said chair and hit my head on the side of the table. Only a minor bruise, no short term memory damage, just a minor bruise.

wishes Google would exclude experts-exchange from ALL search results

Just as I really loathe it when people post links on Twitter to articles you have to register to view as I talked about back in March, I really loathe websites that allow their pages to be indexed by search engine spiders but then force you to pay to get to the answer to the question you asked. Worse still, they seem to appear in almost every technical search.

Experts-Exchange isn't the only culprit here, but they're probably the most infamous; heck they even warrant a section on Wikipedia. Even if they consistently had the answers to the questions I seem to want answered, just because of their search engine practises I wouldn't want to support them by paying for their service.

In response to this, I pledge to donate five Australian dollars to the next website that helps me with my technical problems if they have a tip jar or similar service. I will chronicle the site here when I find it.

I reckon sometimes the best way to deal with negative actions is with positive actions.


Java ArrayIndexOutOfBoundsException

Starbucks cups

Because I'm studying full time again after having a leave of absence and studying part time, all my classes (get it!?) are out of whack. For example I've started Java again this semester and I'm hopelessly rusty! One problem I'm having is creating an object array, assigning objects to it, then attempting to use methods from the objects in a loop.

Simple, right? Whenever I try, I get the following error:

Exception in thread "main" \
java.lang.ArrayIndexOutOfBoundsException: [x]

I'm not attempting to access objects that don't exist in the array, I'm using the array.count() method to only loop through the ones I know exist. Still, the error persists and it's driving me crazy!

Here's the problem reproduced in a very basic example. I'm creating a Market object, adding a series of Stall objects (which number to less than 10!), then attempting to read the toString() methods for each Stall in the Market.

Stall.java

public class Stall {
   String name = "Vacant";

   public Stall(String name) {
      this.name = name;
   }

   public String toString() {
      return name;
   }
}

Market.java

public class Market {
   private Stall stalls[] = new Stall[10];

   public void addStall(Stall a) {
      stalls[stalls.length] = a;
   }

   public String toString() {
      String toReturn = "";
      for (int count = 0; count < stalls.length; count++) {
         toReturn += (stalls[stalls.length] + " ");
      }
      return toReturn;
   }
}

TestMarket.java

public class TestMarket {
  public static void main(String[] args) {
    Stall coffeeBean = new Stall("Coffee Bean and Tea Leaf");
    Stall starbucks = new Stall("Starbucks");
    Market rundleMall = new Market();

    rundleMall.addStall(coffeeBean);
    rundleMall.addStall(starbucks);

    System.out.println(rundleMall);
  }
}

The thing I'm doing wrong is probably breathtakingly obvious, but I've been staring at this for hours and can't figure it out. The only way I've been able to fix it is to wrap the inside of each for loop in a try statement and catch ArrayIndexOutOfBoundsException which is hardly an ideal solution!