Wednesday, February 17, 2010

Java: ==, .equals(), compareTo(), and compare()

Java: ==, .equals(), compareTo(), and compare()

Equality comparison: One way for primitives, Four ways for objects

Comparison Primitives Objects
a == b, a != bEqual values Compares references, not values. The use of == with object references is generally limited to the following:
  • Comparing to see if a reference is null.
  • Comparing two enum values. This works because there is only one object for each enum constant.
  • You want to know if two references are to the same object
a.equals(b) N/A Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

It turns out that defining equals() isn't trivial; in fact it's moderately hard to get it right, especially in the case of subclasses. The best treatment of the issues is in Horstmann's Core Java Vol 1. [TODO: Add explanation and example]

a.compareTo(b)N/A Comparable interface. Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a natural order, implement the Comparable interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).
compare(a, b)N/A Comparator interface. Compares values of two objects. This is implemented as part of the Comparator interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such as sort() or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following.
  • Multiple comparisions. To provide several different ways to sort somthing. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the sort() method.
  • System class. To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
  • Strategy pattern. To implement a Strategey pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.

If your class objects have one natural sorting order, you may not need this.

Comparing Object references with the == and != Operators

The two operators that can be used with object references are comparing for equality (==) and inequality (!=). These operators compare two values to see if they refer to the same object. Although this comparison is very fast, it is often not what you want.

Usually you want to know if the objects have the same value, and not whether two objects are a reference to the same object. For example,

if (name == "Mickey Mouse")   // Legal, but ALMOST SURELY WRONG

This is true only if name is a reference to the same object that "Mickey Mouse" refers to. This will be false if the String in name was read from input or computed (by putting strings together or taking the substring), even though name really does have exactly those characters in it.

Many classes (eg, String) define the equals() method to compare the values of objects.

Comparing Object values with the equals() Method

Use the equals() method to compare object values. The equals() method returns a boolean value. The previous example can be fixed by writing:

if (name.equals("Mickey Mouse"))  // Compares values, not refererences.

Because the equals() method makes a == test first, it can be fairly fast when the objects are identical. It only compares the values if the two references are not identical.

Other comparisons - Comparable interface

The equals method and == and != operators test for equality/inequality, but do not provide a way to test for relative values. Some classes (eg, String and other classes with a natural ordering) implement the Comparable interface, which defines a compareTo method. You will want to implement Comparable in your class if you want to use it with Collections.sort() or Arrays.sort() methods.

Defining a Comparator object

As described in the table above on compare(), you can create Comparators to sort any arbitrary way for any class. For example, the String class defines the CASE_INSENSITIVE_ORDER comparator.

If you override equals, you should also override hashCode()

Overriding hashCode(). The hashCode() method of a class is used for hashing in library data structures such as HashSet and HashMap. If you override equals(), you should override hashCode() or your class will not work correctly in these (and some other) data structures.

Shouldn't .equals and .compareTo produce same result?

The general advice is that if a.equals(b) is true, then a.compareTo(b) == 0 should also be true. Curiously, BigDecimal violates this. Look at the Java API documentation for an explanation of the difference. This seems wrong, although their implementation has some plausibiliby.

Other comparison methods

String has the specialized equalsIgnoreCase() and compareToIgnoreCase(). String also supplies the constant String.CASE_INSENSITIVE_ORDER Comparator.

The === operator (Doesn't exist - yet?)

Comparing objects is somewhat awkward, so a === operator has been proposed. One proposal is that
a === b would be the same as ((a == b) || ((a != null) && a.equals(b)))

Common Errors

Using == instead of equals() with Objects
When you want to compare objects, you need to know whether you should use == to see if they are the same object, or equals() to see if they may be a different object, but have the same value. This kind of error can be very hard to find.

Tuesday, February 16, 2010

25+ Alternative & Open Source Database Engines

25+ Alternative & Open Source Database Engines: "

Almost every web developer has a favorite database that he/she feels comfortable working with as all the tricks & gimmicks are already experienced.


It can be one of the popular databases below:



or even simpler ones like XML, text, etc.


It is understandable why these databases are frequently used; they are well-documented, have a community behind them, integrated with most popular CMSs', easy-to-use, offered by most of the hosting companies ,etc..


But there are also many other databases which are getting popular day-by-day & may have advantages over what you're already using.


Here are 25+ open source alternative databases that you may consider using in your next project:


MongoDB


MongoDB


It is an open source, high-performance, scalable, schema-free & document-oriented (JSON-like data schemas) database.


There are ready to use drivers for most popular programming languages like PHP,Python, Perl, Ruby, JavaScript, C++ + more.


Hypertable


Hypertable


Hypertable is a high performance distributed data storage system designed to support applications requiring maximum performance, scalability, and reliability.


It is modeled after Google's BigTable and mostly focuses on large-scale datasets.


Apache CouchDB


Apache CouchDB


A document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript.


CouchDB offers a RESTful JSON API which can be accessed from any environment allowing HTTP requests



Neo4j


Neo4j Graph Database


It is an embedded, disk-based, and fully transactional Java persistence engine that stores data structured in graphs rather than tables.


Neo4j offer a massive scalability. It can handle graphs of several billion nodes/relationships/properties on a single machine and can be scaled across multiple machines.


Riak


Riak


Riak is a very ideal database for web applications as it combines:



  • a decentralized key-value store

  • a flexible map/reduce engine

  • a friendly HTTP/JSON query interface.


Oracle Berkeley DB


Oracle Berkeley DB


It is an embeddable database engine that provides developers with fast, reliable, local persistence with zero administration.


Oracle Berkeley DB is a library that links directly into your application & enables you to make simple function calls rather than sending messages to a remote server for a better performance.


Apache Cassandra


Apache Cassandra


Cassandra is a highly scalable second-generation distributed database that is used by giants like Facebook, Digg, Twitter, Cisco & more..


It aims to provide a consistent, fault-tolerant & highly available environment for storing data.


Memcached


Memcached


Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.


It is intended for use in speeding up dynamic web applications by alleviating database load.


Firebird


Firebird


Firebird is a relational database that can run on Linux, Windows & various UNIX platforms.


It offers high performance and powerful language support for stored procedures and triggers.


Redis


Redis


Redis is an advanced fast key-value database written in C which can be used like memcached, in front of a traditional database, or on its own.


It has support for many programming languages & used by popular projects like GitHub or Engine Yard.


There is also a PHP client named Rediska for managing Redis databases.


HBase


Hadoop HBase


HBase is a distributed & column-oriented store which can also be called as the Hadoop database.


The project aims to host very large tables like "billions of rows, millions of columns".


It has a REST-ful web service gateway that supports XML, Protobuf, and binary data encoding options.


Keyspace


Keyspace


It is a consistently replicated, fault-tolerant key-value store that works in Windows OS.


Keyspace offers high availability by masking server/network failures & appearing as a single, highly available service.


4store


4store


4store is a database storage and query engine that holds RDF data.


It is written in ANSI C99, designed to run on UNIX-like systems & offers a high performance, scalable & stable platform.


MariaDB


MariaDB


MariaDB is a backward compatible, drop-in replacement branch of the MySQL® Database Server.


It includes all major open source storage engines + the Maria storage engine.


Drizzle


Drizzle


It is a fork of MySQL that focuses on being a reliable database optimized for Cloud and Net applications.


HyperSQL


HyperSQL


It is a SQL relational database engine written in Java.


HyperSQL offers a small & fast database engine which has in-memory and disk-based tables, supports embedded/server modes.


Also, it has tools such as a command line SQL tool & GUI query apps.


MonetDB


MonetDB


MonetDB is a database system for high-performance applications in data mining, OLAP, GIS, XML Query, text & multimedia retrieval.


Others



Special Downloads:

Ajaxed Add-To-Basket Scenarios With jQuery And PHP

Free Admin Template For Web Applications

jQuery Dynamic Drag’n Drop

ScheduledTweets


Advertisements:

SSLmatic – Cheap SSL Certificates (from $19.99/year)

Follow WebResourcesDepot At Twitter And Get More Resources!



Tags: , ,


Related posts






"

17 Google Chrome Extensions for Web Designers and Developers

17 Google Chrome Extensions for Web Designers and Developers: "

Firefox is the browser of choice for most designers and developers in part because of the vast selection of add ons that are available. While Chrome does not offer anywhere close to as many extensions (yet), there are still a number that can be very handy for designers and developers. In some cases they are not as robust as the Firefox versions (example, Firebug and Firebug Lite), but if you are using Chrome you may be interested to know about the extensions that are available. Additionally, Chrome comes with some developer tools built in.


In this post we’ll feature 17 of the most useful Chrome extensions for designers and developers. Hopefully in time the selection and quality of Chrome extensions will be able to rival those of Firefox.


Speed Tracer


Speed Tracer is a tool to help you identify and fix performance problems in your web applications. It visualizes metrics that are taken from low level instrumentation points inside of the browser and analyzes them as your application runs. Speed Tracer is available as a Chrome extension and works on all platforms where extensions are currently supported (Windows and Linux).


Speed Tracer


Firebug Lite


Firebug Lite is a tool for web developers, that allows you to edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.


Firebug Lite


Pendule


Pendule displays linked and embedded style sheets of the current page in a new tab. It reloads the style sheets for the current page on the fly, so you don’t have to reload the whole page for each change, and also disables CSS for the current page.


Pendule


Eye Dropper


Eye Dropper and Color Picker extension which allows you to pick color from any webpage or from advanced color picker.


Eye Dropper


Aviary Screen Capture


With Aviary Screen Capture you can take a screenshot of any webpage and edit it directly in your browser with Aviary.com applications. Plus convenient access to the Aviary website and tools.


Aviary Screen Capture


PlainClothes


PlainClothes styles — or rather “unstyles” — the web. Just imagine: text is black, backgrounds are white, unread links are blue, visited links are purple, all links are underlined. Or any other colors you like. And all text is rendered in your default fonts (as defined in “Options” > “Under the Hood” > “Change font and language settings”). Everywhere. Automatically.


PlainClothes


Chrome Sniffer


Chrome Sniffer will help web developers to inspect web framework / CMS and javascript libraries running on websites while browsing. An icon will appear on the address bar indicating the detected framework.


Chrome Sniffer


Lorem Ipsum Generator


The Lorem Ipsum Generator extension creates random dummy “Lorem Ipsum” text.


Lorem Ipsum Generator


Chrome SEO


The Google Chrome SEO Extension provides easy access to Search Engine Optimization Tools that can help you with Competitive Analysis, Keyword Research, Backlink Checks, PageRank Checks and other daily SEO tasks.


Chrome SEO


IE Tab


IE Tab will allow you to use Internet Explorer to display web pages in a Chrome tab. Some sites can only be displayed using IE, and with this extension you can now see those sites without leaving Chrome. Great for web developers who want to test the IE rendering engine, users who use sites with ActiveX controls, and users who want to use the explorer view for local files (i.e. file:// URLs).


IE Tab


Resolution Test


Resolution Test is an extension for developers to test web pages in different screen resolutions, with an option to define your own resolutions.


Resolution Test


MeaureIt!


With MeasureIt! you can draw out a ruler that will help you get the pixel width and height of any elements on a webpage.


MeaureIt!


Validity


Validity can be used to quickly validate your HTML documents from the address bar. Just click the icon in the address bar to validate the current document without leaving the page. The number of validation errors can be seen in the tool tip.


Validity


Snippy


Snippy allows you to grab snippets of web pages and save them for future use. Snippy capture rich contents and preserves formatting, so you can capture paragraphs, images, links and more.


Snippy


META SEO Inspector


META SEO Inspector can be useful to inspect the meta data found inside web pages, usually not visible while browsing.


META SEO Inspector


LastPass


LastPass is a free online password manager and Form Filler that makes your web browsing easier and more secure.


LastPass


Google Tasks


The Google Tasks extension allows you to access Google Tasks from any web page at any time. Great for just jotting something down or checking your agenda.


Google Tasks


For more design resources please see:





"

A new global visual language for the BBC's digital services

A new global visual language for the BBC's digital services: "

The BBC website began its official life back in December 1997 with this very simple design.



1-BBC-homepage-1996.jpg



It was a basic offering with two sections to the site. Over time it has grown to encompass a great deal more. However due to the organic way in which the website evolved and the old structure of the business, with dozens of small design teams working independently of each other, the site had a fairly schizophrenic nature once you delved into its depths.



About 2 years ago, after printing out the site onto what has now become jokingly known as the 'Wall of Shame' we decided to embark on an ambitious project, called Global Visual Language 2.0, with the aim of unifying the visual and interaction design of bbc.co.uk and the mobile website.



2-Wall-of-shame.jpg



We created a new wider, centred page template to take advantage of wider screen resolutions and for the first time created an underlying grid.



3-GVL2-Grid.jpg



We rationalised the hundreds of different banner styles into a new global and local branding and navigation system.



4-GVL2-MAsthead.jpg



We discontinued the scores of different audio and video players and created a universal embedded media player.



5-GVL2-EMP.jpg



And we redesigned the homepage creating a visual style that began to ripple through the site and onto the mobile platform.



6-GVl2-Homepage.jpg



7-Mobile.jpg



We've lived with and loved the distinctly 'web 2.0' design for a while now and it's done us proud. However, time's moved on, and in autumn last year we decided it was time to resurrect the project.



We set out to broaden our ambitions; to create a design philosophy and world-class design standards that all designers across the business could adhere to. We wanted to find the soul of the BBC. We wanted something distinctive and recognisable; we wanted drama. We knew whatever we created needed to be truly cross-platform and that we needed to simplify our user journeys.



We didn't do it on our own. We pulled together representatives from across the business, led by the project's Creative Director, Ben Gammon, to form a Global Design Working Group, and we created a GVL Steering Group to help manage and direct the course of the project. We also went out into the industry to find a partner to co-create the styleguide: Neville Brody and his agency, Research Studios.



8-Neville-Brody.jpg



After going through a tender process in which we invited six agencies to pitch for the work, we chose Research Studios because we felt they had demonstrated a good insight into the BBC, its public purposes and they way in which it functions. We were also impressed with the work created for the pitch and Neville's back catalogue of work.



Together, over the last four months, we've spent countless hours and created countless iterations of designs, components, mastheads, footers, polar maps, word documents, pdfs and grids... and whilst it's still a work in progress, I'd like to share with you where we're at with both the design philosophy and the latest version of our global visual language styleguide.



We wanted to create a design philosophy, or a set of values, to unite the user experience practitioners across the business. We settled on nine keywords which we think sum up what we're about and what we're trying to achieve:



Modern British

We want to create a modern British design aesthetic, something vibrant and quirky that translates outside our national boundaries.



Current

It needs to feel current and reflect what's happening in the UK right now, in real-time. We curate a timeline of Britain and create links to the past - to our rich archive.



Authentic

Wherever we are heard we need to sound authentic and relevant, warm and human. We want to reference the BBC's iconic design and broadcasting heritage. We value the trust placed in us.



Compelling

We engage our audiences with compelling storytelling. Our voice ranges from serious and authoritative through to witty and entertaining.



Distinctive

We stand out from the crowd. We strike a balance between overly templated, cookie-cutter design and beautiful anarchy. We are bold and dramatic.



Pioneering

We pioneer design innovations that surprise and delight. But we take our audiences with us.



Joined-up

We view all services and platforms as one connected whole but deliver experiences that are sensitive to their context of use.



Universal

Our services are open and accessible. Our interfaces are simple, useful and intuitive.



Best

Our ambition is to be the best digital media brand in the world.



Armed with our new philosophy we began creating conceptual designs for various properties: BBC news, homepage, search, iPlayer, programme pages and the embedded media player.



9-GVl3-Workspace.jpg



Through doing this work we began to distill the essence of a new visual style. I'm going to take you through some of the key elements, starting with the page grid.



We took inspiration from many sources. What we were trying to achieve is an underlying grid system that was flexible enough to enable many unique design variations whilst still feeling coherent and considered.



10-Penguin.jpg



The new grid is based on 31 sixteen pixel columns with two left hand columns that can be split into four, and one wider right hand column, which accommodates the ad formats that appear on the international facing version of the site.



11-grid.jpg



We're looking to create the effect of interwoven vertical and horizontal bands, making a feature of the right hand column across the site.



12-grid.jpg



Along with the 16 pixel vertical grid we've also for the first time got an integrated 8 pixel baseline grid so that we can align elements on a page both vertically and horizontally.



13-baseline.jpg



A key feature of the new GVL is a much more dramatic use of typography. As well as Gill Sans we've introduced big bold type in Helvetica or Arial and restricted variations in size so that we have much greater consistency across the site.



14-type.gif



Here's an example of it all pulled together on a new story page, and examples of typography styling in promo drawers. We focused on signposting and articulation; you can see the time stamping treatment and signposting for live content.



15-type.jpg



16-type.jpg



This is an example of a call to action for a piece of video and a pull quote. You can see again the dramatic use of typography and big bold iconography.



17-type.jpg



Here's another couple of examples of typographic styling; type over images and the use of scale to create hierarchy and drama in link styling.



18-TYPE.jpg



19-type.jpg



We've developed a highlight colour palette for non-branded areas of the site, or areas where the BBC masterbrand talks directly to the audience (eg the BBC homepage, search, some of our genre areas). Each colour has a tonal range to be used in contrast or in unison with each other.



20-colour.jpg



We've also got a neutral palette and a much more restrained usage of gradients where the colours are situated next to each other in each tonal range on the colour wheel.



21-colour.jpg



22-coloour.jpg



Our recommendation is that pages have a predominantly neutral colour palette with colour being provided by large and dramatic imagery. The highlight colour is used sparingly to create vibrancy and draw the eye to key areas of the page.



23-colour.jpg



We're moving away from left hand navigation to consistently placed, horizontal navigation across the site. Here's an example from Sport:



24-nav.jpg



We're designing a new look and feel for the embedded media player - it's still a work in progress but you can see the bold calls to action and typography.



25-EMP.jpg



We've got four types of carousel - one that fits right hand column, one for the double left hand columns, a full-width version and one that breaks out of the page grid and extends to the browser edges to create a cinematic, full screen experience.



26-carousels.jpg



And finally, we've created a new set of icons.



27-icons.jpg



This style guide is a set of page elements that can be pulled together in any number of ways. We wanted to create something that is flexible enough to allow all our brands their full expression whilst uniting them into a coherent user experience. We also wanted to strip out any superfluous decoration and allow the content and imagery to shine through. To me, this new visual language is exciting and refreshing. It feels timeless, yet very of the moment. I hope you agree.



Next steps; we need to finalise the masthead and footer. We're looking at mobile and IPTV as well how we treat social elements on the page (social bookmarking, share functionality, comments, ratings, reviews etc). We'll also be working through the components in the glow widget library and pulling it all together into an audience-facing design and code patterns library along with a new set of standards and guidelines.



I hope you like what you see. We're always interested in your feedback on both the philosophy and the styleguide.



Bronwyn van der Merwe is Head of Design and User Experience, Central Team, BBC FM&T.

"