Friday, October 12, 2007

Java Faqs - How can I program linked lists if Java doesn't have pointers?

Of all the misconceptions about Java, this is the most egregious. Far from not having pointers, in Java, object-oriented programming is conducted exclusively with pointers. In other words, objects are only ever accessed through pointers, never directly. The pointers are termed "references" and they are automatically dereferenced for you.Java does not have pointer arithmetic or untyped casting. By removing the ability for programmers to create and modify pointers in arbitrary ways, Java makes memory management more reliable, while still allowing dynamic data structures. Also note that Java has NullPointerException, not NullReferenceException.A linked list class in Java might start like this:public class LinkedList {public LinkedList head;public LinkedList next;public Object data;public LinkedList advanceToNext(LinkedList current) { ...}Another choice for a linked list structure is to use the built-in class java.util.Vector which accepts and stores arbitrary amounts of Object data (as a linked list does), and retrieves it by index number on demand (as an array does). It grows automatically as needed to accommodate more elements. Insertion at the front of a Vector is a slow operation compared with insertion in a linked list, but retrieval is fast. Which is more important in the application you have!.
Note: java.util.Vector is thread safety.. so it is slow. If you are not worried about thead safety, it is better to user java.util.List.

By

Shantan Nethikar

99490401096

No comments: