Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

100 Recipes for Programming Java
100 Recipes for Programming Java
100 Recipes for Programming Java
Ebook1,671 pages12 hours

100 Recipes for Programming Java

Rating: 4.5 out of 5 stars

4.5/5

()

Read preview

About this ebook

Java Recipes are structured in a Cookbook format featuring recipes that contain problem statements and solutions. A detailed explanation follows each problem statement of the recipe. This is usually contained within the solution; however, an optional discussion section can often contain other useful information helping to demonstrate how the solution works.

Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!

LanguageEnglish
PublisherJamie Munro
Release dateAug 11, 2017
ISBN9781370619450
100 Recipes for Programming Java
Author

Jamie Munro

I have been developing websites both personally and professionally for the past 15 years. During this time I’ve helped engineer dozens of small and large projects using CakePHP as the framework. The ideas and methodologies behind this book all stem from my experience with providing quality web applications to my clients. I am well versed in many web technologies as well as several software development languages. My brain is constantly working as I’m always looking to better myself as I strive to continue my role as lead developer. For more information, visit my blog at http://www.endyourif.com

Read more from Jamie Munro

Related to 100 Recipes for Programming Java

Related ebooks

Programming For You

View More

Related articles

Reviews for 100 Recipes for Programming Java

Rating: 4.5 out of 5 stars
4.5/5

2 ratings1 review

What did you think?

Tap to rate

Review must be at least 10 words

  • Rating: 5 out of 5 stars
    5/5
    very useful stack overflow q&a compilations. I really liked the concept of this book

    1 person found this helpful

Book preview

100 Recipes for Programming Java - Jamie Munro

100 Recipes for Programming Java

Organized by: Jamie Munro

This book is dedicated to the user's of StackOverFlow who have asked over 1,300,000 questions at the time this book was organized.

Preface

About the Book

This book is structured in a Cookbook format featuring recipes that contain problem statements and solutions. A detailed explanation follows each problem statement of the recipe. This is usually contained within the solution; however, an optional discussion section can often contain other useful information helping to demonstrate how the solution works.

The Recipes

Differences between HashMap and Hashtable?

How to convert number to words in java

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

Unfortunately MyApp has stopped. How can I solve this?

Parsing JSON string in Java

What does "Could not find or load main class" mean?

How do I tell Maven to use the latest version of a dependency?

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

Working Soap client example

How to do a SOAP Web Service call from Java class?

How to generate a random alpha-numeric string?

When to use LinkedList over ArrayList?

Why is it faster to process a sorted array than an unsorted array?

Write string to output stream

Avoiding != null statements

Downloading Java JDK on Linux via wget is shown license page instead

How to handle invalid SSL certificates with Apache HttpClient?

Java string to date conversion

How to get the current date/time in Java

Difference between wait() and sleep()

Type safety: Unchecked cast

How to split a string in Java

Why doesn't RecyclerView have onItemClickListener()?

What does a "Cannot find symbol" compilation error mean?

Java: how can I split an ArrayList in multiple small ArrayLists?

Sending Email in Android using JavaMail API without using the default/built-in app

Best practice for REST token-based authentication with JAX-RS and Jersey

How to remove special characters from a string?

Adding JPanel from another class to JPanel in JFrame

How to obtain the start time and end time of a day?

Why is exception.printStackTrace() considered bad practice?

Spring context from within a jar file

Spring - @Transactional - What happens in background?

IDEA: javac: source release 1.7 requires target release 1.7

Java GUI: How to Set Focus on JButton in JPanel on JFrame?

Why is it bad practice to call System.gc()?

Difference between Static and final?

How to gracefully handle the SIGKILL signal in Java

What does "implements" do on a class?

How do you have the code pause for a couple of seconds in android?

Java - Decimal Format.parse to return double value with specified number of decimal places

calling java methods in javascript code

Get Cell Value from Excel Sheet with Apache Poi

Fastest way to iterate over all the chars in a String

Get request parameter values in JSF

RESTful Authentication via Spring

what are good blogs to read relating java, spring, hibernate, maven?

Should I use Vaadin Framework

Convert .csv to .xls in Java

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

Memory overhead of Java HashMap compared to ArrayList

What to put into jta-data-source of persistence.xml?

Setting Range for X,Y Axis-JfreeChart

What exactly is Spring Framework for?

Implement custom AuthenticationProvider in Spring Security 2.06

How to do a JUnit assert on a message in a logger

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Java executors: how to be notified, without blocking, when a task completes?

XSS prevention in JSP/Servlet web application

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

Core difference between object oriented and object based language

Java: unparseable date exception

Hashmap.keySet(), foreach, and remove

java.util.regex - importance of Pattern.compile()?

Mockito to test void methods

Why are only final variables accessible in anonymous class?

Maven is not working in Java 8 when Javadoc tags are incomplete

How to escape comma and double quote at same time for CSV file?

Java: how do I get a class literal from a generic type?

C# var keyword equivalent in java?

SOAP request to WebService with java

Java string replace and the NUL (NULL, ASCII 0) character?

Spring Data JPA - injection fails - BeanCreationException: Could not autowire field

What is the difference between "text" and new String("text")?

How to test that no exception is thrown?

difference between HashMap and ArrayList in java?

Servlet Mapping using web.xml

Best OS for java development?

java: what is this: [Ljava.lang.Object;?

javax.naming.NameNotFoundException

How to configure environment to use JavaMail?

How can I fill a combobox with values in a database?

init-param and context-param

Retain precision with double in Java

Can not find the tag library descriptor for http://java.sun.com/jsp/jstl/core

The Use of Multiple JFrames: Good or Bad Practice?

Java Serialization with non serializable parts

Question about Hibernate session.flush()

What is the convention for word separator in Java package names?

Gson and deserializing an array of objects with arrays in it

Java SSL/TLS ignore expired cert? (java.security.cert.CertPathValidatorException: timestamp check failed)

Does Java SE 8 have Pairs or Tuples?

How do I use Google's Gson API to deserialize JSON properly?

Detecting if a string has unique characters: comparing my solution to "Cracking the Coding Interview?"

How to get the fields in an Object via reflection?

How do a send an HTTPS request through a proxy in Java?

Subclipse and JavaHL installation headache

How to read and write xml files?

Differences between HashMap and Hashtable?

Problem

What are the differences between a HashMap and a Hashtable in Java?

Which is more efficient for non-threaded applications?

Problem courtesy of: dmanxiii

Solution

There are several differences between HashMap and Hashtable in Java:

Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.

Solution courtesy of: Josh Brown

Discussion

Based on the info here, I'd recommend going with HashMap. I think the biggest advantage is that Java will prevent you from modifying it while you are iterating over it, unless you do it through the iterator.

Discussion courtesy of: pkaeding

Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.

For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.

Discussion courtesy of: izb

Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.

Discussion courtesy of: Miles D

In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.

Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.

Discussion courtesy of: matt b

For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.

Discussion courtesy of: Tim Howland

HashMap: An implementation of the Map interface that uses hash codes to index an array. Hashtable: Hi, 1998 called. They want their collections API back.

Seriously though, you're better off staying away from Hashtable altogether. For single-threaded apps, you don't need the extra overhead of syncrhonisation. For highly concurrent apps, the paranoid synchronisation might lead to starvation, deadlocks, or unnecessary garbage collection pauses. Like Tim Howland pointed out, you might use ConcurrentHashMap instead.

Discussion courtesy of: Apocalisp

Note, that a lot of the answers state that Hashtable is synchronised. In practice this buys you very little. The synchronization is on the accessor / mutator methods will stop two threads adding or removing from the map concurrently, but in the real world you will often need additional synchronisation.

A very common idiom is to check then put - i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.

An equivalently synchronised HashMap can be obtained by:

Collections.synchronizedMap(myMap);

But to correctly implement this logic you need additional synchronisation of the form:

synchronized(myMap) {

    if (!myMap.containsKey(tomato))

        myMap.put(tomato, red);

}

Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.

Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:

ConcurrentMap.putIfAbsent(key, value);

Discussion courtesy of: serg10

No one's mentioned the fact that Hashtable is not part of the Java Collections Framework - it just provides a similar API. Also, Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.

Discussion courtesy of: aberrant80

Another key difference between hashtable and hashmap is that Iterator in the HashMap is fail-fast while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort."

My source: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html

Discussion courtesy of: Neerja

This question is often asked in interview to check whether candidate understands correct usage of collection classes and is aware of alternative solutions available.

The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

HashMap does not guarantee that the order of the map will remain constant over time.

HashMap is non synchronized whereas Hashtable is synchronized.

Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.

Note on Some Important Terms

Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object structurally, a concurrent modification exception will be thrown. It is possible for other threads though to invoke set method since it doesn't modify the collection structurally. However, if prior to calling set, the collection has been modified structurally, IllegalArgumentException will be thrown.

Structurally modification means deleting or inserting element which could effectively change the structure of map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.

The Map Interface

Discussion courtesy of: sravan

Beside all the other important aspects already mentioned here, Collections API (e.g. Map interface) is being modified all the time to conform to the latest and greatest additions to Java spec.

For example, compare Java 5 Map iterating:

for (Elem elem : map.keys()) {

  elem.doSth();

}

versus the old Hashtable approach:

for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {

  Elem elem = (Elem) en.nextElement();

  elem.doSth();

}

In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:

Map map = { orange : 12, apples : 15 };

map[apples];

Update: No, they won't land in 1.8... :(

Are Project Coin's collection enhancements going to be in JDK8?

Discussion courtesy of: pwes

HashTable is synchronized, if you are using it in a single thread you can use HashMap, which is an unsynchronized version. Unsynchronized objects are often a little more performant. By the way if multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. Youn can wrap a unsynchronized map in a synchronized one using :

Map m = Collections.synchronizedMap(new HashMap(...));

HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.

The iterators returned by Map are fail-fast, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.

HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).

HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.

HashMap doesn't guarantee the order in which elements are returned. For HashTable I guess it's the same but I'm not entirely sure, I don't find ressource that clearly state that.

Discussion courtesy of: alain.janinm

HashMaps gives you freedom of synchronization and debugging is lot more easier

Discussion courtesy of: user1506047

Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.

Java Collection Matrix

Discussion courtesy of: Sujan

HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap will construct a hash table with power of two size, increase it dynamically such that you have at most about eight elements (collisions) in any bucket and will stir the elements very well for general element types. However, the Hashtable implementation provides better and finer control over the hashing if you know what you are doing, namely you can fix the table size using e.g. the closest prime number to your values domain size and this will result in better performance than HashMap i.e. less collisions for some cases.

Separate from the obvious differences discussed extensively in this question, I see the Hashtable as a manual drive car where you have better control over the hashing and the HashMap as the automatic drive counterpart that will generally perform well.

Discussion courtesy of: Giovanni Azua

1)Hashtable is synchronized whereas hashmap is not. 2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

3)HashMap permits null values in it, while Hashtable doesn't.

Discussion courtesy of: raja

HashMap:- It is a class available inside java.util package and it is used to store the element in key and value format.

Hashtable:-It is a legacy class which is being recognized inside collection framework

Discussion courtesy of: Ankit

HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.

Discussion courtesy of: jontejj

HashMap is emulated and therefore usable in GWT client code whereas Hashtable is not.

Discussion courtesy of: pong

HashMap is a class used to store the element in key and value format.it is not thread safe. because it is not synchronized .where as Hashtable is synchronized.Hashmap permits null but hastable doesn't permit null.

Discussion courtesy of: Ekanta Swain

There are 5 basic differentiations with HashTable and HashMaps.

Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

In Hashtable there is a function contains(), which is very confusing to use. Because the meaning of contains is slightly deviating. Whether it means contains key or contains value? tough to understand. Same thing in Maps we have ContainsKey() and ContainsValue() functions, which are very easy to understand.

In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

HashTables are by default synchronized, so it can be used with multiple threads easily. Where as HashMaps are not synchronized by default, so can be used with only single thread. But you can still convert HashMap to synchronized by using Collections util class's synchronizedMap(Map m) function.

HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.

Discussion courtesy of: user1923551

Since Hashtable in Java is a subclass of Dictionary class which is now obsolete due to the existance of Map Interface it is not used anymore. Moreover there isn't anything you can't do with a class that implements the Map Interface that you can do with a Hashtable.

Discussion courtesy of: PetarMI

My small contribution :

First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.

Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.

Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.

Discussion courtesy of: Shreyos Adikari

Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.

Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.

Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.

enter image description here

Discussion courtesy of: Bin Chen

HashMap and HashTable

Some important points about HashMap and HashTable. please read below details.

1) Hashtable and Hashmap implement the java.util.Map interface 2) Both Hashmap and Hashtable is the hash based collection. and working on hashing. so these are similarity of HashMap and HashTable.

What is the difference between HashMap and HashTable?

1) First difference is HashMap is not thread safe While HashTable is ThreadSafe

2) HashMap is performance wise better because it is not thread safe. while Hashtable performance wise is not better because it is thread safe. so multiple thread can not access Hashtable at the same time.

Discussion courtesy of: JegsVala

Old and classic topic, just want to add this helpful blog that explains this:

http://blog.manishchhabra.com/2012/08/the-5-main-differences-betwen-hashmap-and-hashtable/

Blog by Manish Chhabra

The 5 main differences betwen HashMap and Hashtable

HashMap and Hashtable both implement java.util.Map interface but there are some differences that Java developers must understand to write more efficient code. As of the Java 2 platform v1.2, Hashtable class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework.

One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).

The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.

One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don’t need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.

HashMap does not guarantee that the order of the map will remain constant over time.

Note that HashMap can be synchronized by

Map m = Collections.synchronizedMap(hashMap);

In Summary there are significant differences between Hashtable and HashMap in Java e.g. thread-safety and speed and based upon that only use Hashtable if you absolutely need thread-safety, if you are running Java 5 consider using ConcurrentHashMap in Java.

Discussion courtesy of: Night0

1.Hashmap and HashTable both store key and value.

2.Hashmap can store one key as null. Hashtable can't store null.

3.HashMap is not synchronized but Hashtable is synchronized.

4.HashMap can be synchronized with Collection.SyncronizedMap(map)

Map hashmap = new HashMap();

 

Map map = Collections.SyncronizedMap(hashmap);

Discussion courtesy of: Rahul Tripathi

1.HashMap is non-synchronized whereas Hashtable is synchronized.

2.HashMap does not guarantee that the order of the map will remain constant over time.

3.One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment.

Discussion courtesy of: Chetu

Hashtable:

Hashtable is a data structure that retains values of key-value pair. It doesn’t allow null for both the keys and the values. You will get a NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.

Example :

import java.util.Map;

import java.util.Hashtable;

 

public class TestClass {

 

    public static void main(String args[ ]) {

    Map states= new Hashtable();

    states.put(1, INDIA);

    states.put(2, USA);

 

    states.put(3, null);    //will throw NullPointerEcxeption at runtime

 

    System.out.println(states.get(1));

    System.out.println(states.get(2));

//  System.out.println(states.get(3));

 

    }

}

HashMap:

HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.

Example:

import java.util.HashMap;

import java.util.Map;

 

public class TestClass {

 

    public static void main(String args[ ]) {

    Map states = new HashMap();

    states.put(1, INDIA);

    states.put(2, USA);

 

    states.put(3, null);    // Okay

    states.put(null,UK);

 

    System.out.println(states.get(1));

    System.out.println(states.get(2));

    System.out.println(states.get(3));

 

    }

}

Discussion courtesy of: IntelliJ Amiya

Difference between HashMap and HashTable / HashMap vs HashTable

Synchronization or Thread Safe : This is the most important difference between two . HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized. When to use HashMap ? answer is if your application do not require any multi-threading task, in other words hashmap is better for non-threading applications. HashTable should be used in multithreading applications.

Null keys and null values : Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.

Iterating the values: Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.

Fail-fast iterator : The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not. According to Oracle Docs, if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method , then the iterator will throw ConcurrentModification Exception. Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.We have already explained the difference between iterator and enumeration.

Performance : Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.

Superclass and Legacy : Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the Map abstract data type.

Discussion courtesy of: Moitt

Synchronization or Thread Safe :

Hash Map is not synchronized hence it is not thred safe and it cannot be shared between multiple threads without proper synchronized block whereas, Hashtable is synchronized and hence it is thread safe.

Null keys and null values :

HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.

Iterating the values:

Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method.

Superclass and Legacy :

HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.

Performance :

As HashMap is not synchronized it is faster as compared to Hashtable.

Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection

Discussion courtesy of: amitguptageek

Apart from the differences already mentioned, it should be noted that since Java 8, HashMap dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree), so that even if high hash collisions exist, the worst case when searching is

O(log(n)) for HashMap Vs O(n) in Hashtable.

*The aforementioned improvement has not been applied to Hashtable yet, but only to HashMap, LinkedHashMap, and ConcurrentHashMap.

FYI, currently,

TREEIFY_THRESHOLD = 8 : if a bucket contains more than 8 nodes, the linked list is transformed into a balanced tree.

UNTREEIFY_THRESHOLD = 6 : when a bucket becomes too small (due to removal or resizing) the tree is converted back to linked list.

Discussion courtesy of: Konstantinos Chalkias

Differences between HashMap and Hashtable in Java:

1) Thread Safe

HashTable is internally synchronized.

Therefore, it is very much safe to use HashTable in multi threaded applications.

Where as HashMap is not internally synchronized.

Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization.

You can externally synchronize HashMap using Collections.synchronizedMap() method.

2) Inherited From

Though both HashMap and HashTable implement Map interface, but they extend two different classes.

HashMap extends AbstractMap class where as HashTable extends Dictionary class which is the legacy class in java.

3) Null Keys And Null Values

HashMap allows maximum one null key and any number of null values.

Where as HashTable doesn’t allow even a single null key and null value.

4) Traversal

HashMap returns only Iterators which are used to traverse over the elements of HashMap.

HashTable returns Iterator as well as Enumeration which can be used to traverse over the elements of HashTable.

5) Fail-Fast Vs Fail-Safe

Iterator returned by HashMap are fail-fast in nature i.e they throw ConcurrentModificationException if the HashMap is modified after the creation of Iterator other than iterator’s own remove() method.

On the other hand, Enumeration returned by the HashTable are fail-safe in nature i.e they don’t throw any exceptions if the HashTable is modified after the creation of Enumeration.

6) Performance

As HashTable is internally synchronized, this makes HashTable slightly slower than the HashMap.

7) Legacy Class

HashTable is a legacy class.

It is almost considered as due for deprecation.

Since JDK 1.5, ConcurrentHashMap is considered as better option than the HashTable.

8) Member Of Java Collection Framework

HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK 1.2.

But, HashTable was there before JDK 1.2. From JDK 1.2, it has been made to implement Map interface, making it a member of collection framework.

difference between hashmap and hashtable

Which is more efficient for non-threaded applications?

Hashtable is synchronized, whereas HashMap is not.

This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

Discussion courtesy of: LaKshMi

There is many good answer already posted. I'm adding few new points and summarizing it.

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. But there are many differences between HashMap and Hashtable classes that are given below.

HashMap

1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.

2) HashMap allows one null key and multiple null values.

3) HashMap is a new class introduced in JDK 1.2.

4) HashMap is fast.

5) We can make the HashMap as synchronized by calling this code

Map m = Collections.synchronizedMap(HashMap);

6) HashMap is traversed by Iterator.

7) Iterator in HashMap is fail-fast.

8) HashMap inherits AbstractMap class.

Hashtable

1) Hashtable is synchronized. It is thread-safe and can be shared with many threads.

2) Hashtable doesn't allow any null key or value.

3) Hashtable is a legacy class.

4) Hashtable is slow.

5) Hashtable is internally synchronized and can't be unsynchronized.

6) Hashtable is traversed by Enumerator and Iterator.

7) Enumerator in Hashtable is not fail-fast.

8) Hashtable inherits Dictionary class.

Further reading What is difference between HashMap and Hashtable in Java?

enter image description here

Discussion courtesy of: roottraveller

HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation

Discussion courtesy of: MissFiona

The Hashtable class is synchronized, that is, it is designed to be used by applications that handle multiple or multithreaded process. Synchronized classes are less efficient in the classical case of an application to a process, so the Hashmap class is faster in general. The HashTable class does not accept the Null value, either for keys or for values, while the HashMap class allows a single key with Null and as many as null as possible.

Discussion courtesy of: KB Hassan

This content originated from StackOverFlow and has been re-organized into the above recipe.

How to convert number to words in java

Problem

We currently have a crude mechanism to convert numbers to words (e.g. using a few static arrays) and based on the size of the number translating that into an english text. But we are running into issues for numbers which are huge.

10183 = Ten thousand one hundred eighty three

90 = Ninety

5888 = Five thousand eight hundred eighty eight

Is there an easy to use function in any of the math libraries which I can use for this purpose?

Problem courtesy of: Jason

Solution

Here is the code, I don't think there is any method in SE.

It basically converts number to string and parses String and associates it with the weight

for example

1000

1 is treated as thousand position and 1 gets mapped to one and thousand because of position

This is the code from the website:

English

import java.text.DecimalFormat;

 

public class EnglishNumberToWords {

 

  private static final String[] tensNames = {

    ,

    ten,

    twenty,

    thirty,

    forty,

    fifty,

    sixty,

    seventy,

    eighty,

    ninety

  };

 

  private static final String[] numNames = {

    ,

    one,

    two,

    three,

    four,

    five,

    six,

    seven,

    eight,

    nine,

    ten,

    eleven,

    twelve,

    thirteen,

    fourteen,

    fifteen,

    sixteen,

    seventeen,

    eighteen,

    nineteen

  };

 

  private EnglishNumberToWords() {}

 

  private static String convertLessThanOneThousand(int number) {

    String soFar;

 

    if (number % 100 < 20){

      soFar = numNames[number % 100];

      number /= 100;

    }

    else {

      soFar = numNames[number % 10];

      number /= 10;

 

      soFar = tensNames[number % 10] + soFar;

      number /= 10;

    }

    if (number == 0) return soFar;

    return numNames[number] + hundred + soFar;

  }

 

 

  public static String convert(long number) {

    // 0 to 999 999 999 999

    if (number == 0) { return zero; }

 

    String snumber = Long.toString(number);

 

    // pad with 0

    String mask = 000000000000;

    DecimalFormat df = new DecimalFormat(mask);

    snumber = df.format(number);

 

    // XXXnnnnnnnnn

    int billions = Integer.parseInt(snumber.substring(0,3));

    // nnnXXXnnnnnn

    int millions  = Integer.parseInt(snumber.substring(3,6));

    // nnnnnnXXXnnn

    int hundredThousands = Integer.parseInt(snumber.substring(6,9));

    // nnnnnnnnnXXX

    int thousands = Integer.parseInt(snumber.substring(9,12));

 

    String tradBillions;

    switch (billions) {

    case 0:

      tradBillions = ;

      break;

    case 1 :

      tradBillions = convertLessThanOneThousand(billions)

      + billion ;

      break;

    default :

      tradBillions = convertLessThanOneThousand(billions)

      + billion ;

    }

    String result =  tradBillions;

 

    String tradMillions;

    switch (millions) {

    case 0:

      tradMillions = ;

      break;

    case 1 :

      tradMillions = convertLessThanOneThousand(millions)

        + million ;

      break;

    default :

      tradMillions = convertLessThanOneThousand(millions)

        + million ;

    }

    result =  result + tradMillions;

 

    String tradHundredThousands;

    switch (hundredThousands) {

    case 0:

      tradHundredThousands = ;

      break;

    case 1 :

      tradHundredThousands = one thousand ;

      break;

    default :

      tradHundredThousands = convertLessThanOneThousand(hundredThousands)

        + thousand ;

    }

    result =  result + tradHundredThousands;

 

    String tradThousand;

    tradThousand = convertLessThanOneThousand(thousands);

    result =  result + tradThousand;

 

    // remove extra spaces!

    return result.replaceAll(^\\s+, ).replaceAll(\\b\\s{2,}\\b, );

  }

 

  /**

  * testing

  * @param args

  */

  public static void main(String[] args) {

    System.out.println(*** + EnglishNumberToWords.convert(0));

    System.out.println(*** + EnglishNumberToWords.convert(1));

    System.out.println(*** + EnglishNumberToWords.convert(16));

    System.out.println(*** + EnglishNumberToWords.convert(100));

    System.out.println(*** + EnglishNumberToWords.convert(118));

    System.out.println(*** + EnglishNumberToWords.convert(200));

    System.out.println(*** + EnglishNumberToWords.convert(219));

    System.out.println(*** + EnglishNumberToWords.convert(800));

    System.out.println(*** + EnglishNumberToWords.convert(801));

    System.out.println(*** + EnglishNumberToWords.convert(1316));

    System.out.println(*** + EnglishNumberToWords.convert(1000000));

    System.out.println(*** + EnglishNumberToWords.convert(2000000));

    System.out.println(*** + EnglishNumberToWords.convert(3000200));

    System.out.println(*** + EnglishNumberToWords.convert(700000));

    System.out.println(*** + EnglishNumberToWords.convert(9000000));

    System.out.println(*** + EnglishNumberToWords.convert(9001000));

    System.out.println(*** + EnglishNumberToWords.convert(123456789));

    System.out.println(*** + EnglishNumberToWords.convert(2147483647));

    System.out.println(*** + EnglishNumberToWords.convert(3000000010L));

 

    /*

    *** zero

    *** one

    *** sixteen

    *** one hundred

    *** one hundred eighteen

    *** two hundred

    *** two hundred nineteen

    *** eight hundred

    *** eight hundred one

    *** one thousand three hundred sixteen

    *** one million

    *** two millions

    *** three millions two hundred

    *** seven hundred thousand

    *** nine millions

    *** nine millions one thousand

    *** one hundred twenty three millions four hundred

    **      fifty six thousand seven hundred eighty nine

    *** two billion one hundred forty seven millions

    **      four hundred eighty three thousand six hundred forty seven

    *** three billion ten

    **/

  }

}

Français Quite different than the english version but french is a lot more difficult!

package com.rgagnon.howto;

 

import java.text.*;

 

class FrenchNumberToWords {

  private static final String[] dizaineNames = {

    ,

    ,

    vingt,

    trente,

    quarante,

    cinquante,

    soixante,

    soixante,

    quatre-vingt,

    quatre-vingt

  };

 

  private static final String[] uniteNames1 = {

    ,

    un,

    deux,

    trois,

    quatre,

    cinq,

    six,

    sept,

    huit,

    neuf,

    dix,

    onze,

    douze,

    treize,

    quatorze,

    quinze,

    seize,

    dix-sept,

    dix-huit,

    dix-neuf

  };

 

  private static final String[] uniteNames2 = {

    ,

    ,

    deux,

    trois,

    quatre,

    cinq,

    six,

    sept,

    huit,

    neuf,

    dix

  };

 

  private FrenchNumberToWords() {}

 

  private static String convertZeroToHundred(int number) {

 

    int laDizaine = number / 10;

    int lUnite = number % 10;

    String resultat = ;

 

    switch (laDizaine) {

    case 1 :

    case 7 :

    case 9 :

      lUnite = lUnite + 10;

      break;

    default:

    }

 

    // séparateur - et 

    String laLiaison = ;

    if (laDizaine > 1) {

      laLiaison = -;

    }

    // cas particuliers

    switch (lUnite) {

    case 0:

      laLiaison = ;

      break;

    case 1 :

      if (laDizaine == 8) {

        laLiaison = -;

      }

      else {

        laLiaison = et ;

      }

      break;

    case 11 :

      if (laDizaine==7) {

        laLiaison = et ;

      }

      break;

    default:

    }

 

    // dizaines en lettres

    switch (laDizaine) {

    case 0:

      resultat = uniteNames1[lUnite];

      break;

    case 8 :

      if (lUnite == 0) {

        resultat = dizaineNames[laDizaine];

      }

      else {

        resultat = dizaineNames[laDizaine]

                                + laLiaison + uniteNames1[lUnite];

      }

      break;

    default :

      resultat = dizaineNames[laDizaine]

                              + laLiaison + uniteNames1[lUnite];

    }

    return resultat;

  }

 

  private static String convertLessThanOneThousand(int number) {

 

    int lesCentaines = number / 100;

    int leReste = number % 100;

    String sReste = convertZeroToHundred(leReste);

 

    String resultat;

    switch (lesCentaines) {

    case 0:

      resultat = sReste;

      break;

    case 1 :

      if (leReste > 0) {

        resultat = cent + sReste;

      }

      else {

        resultat = cent;

      }

      break;

    default :

      if (leReste > 0) {

        resultat = uniteNames2[lesCentaines] + cent + sReste;

      }

      else {

        resultat = uniteNames2[lesCentaines] + cents;

      }

    }

    return resultat;

  }

 

  public static String convert(long number) {

    // 0 à 999 999 999 999

    if (number == 0) { return zéro; }

 

    String snumber = Long.toString(number);

 

    // pad des 0

    String mask = 000000000000;

    DecimalFormat df = new DecimalFormat(mask);

    snumber = df.format(number);

 

    // XXXnnnnnnnnn

    int lesMilliards = Integer.parseInt(snumber.substring(0,3));

    // nnnXXXnnnnnn

    int lesMillions  = Integer.parseInt(snumber.substring(3,6));

    // nnnnnnXXXnnn

    int lesCentMille = Integer.parseInt(snumber.substring(6,9));

    // nnnnnnnnnXXX

    int lesMille = Integer.parseInt(snumber.substring(9,12));

 

    String tradMilliards;

    switch (lesMilliards) {

    case 0:

      tradMilliards = ;

      break;

    case 1 :

      tradMilliards = convertLessThanOneThousand(lesMilliards)

        + milliard ;

      break;

    default :

      tradMilliards = convertLessThanOneThousand(lesMilliards)

        + milliards ;

    }

    String resultat =  tradMilliards;

 

    String tradMillions;

    switch (lesMillions) {

    case 0:

      tradMillions = ;

      break;

    case 1 :

      tradMillions = convertLessThanOneThousand(lesMillions)

        + million ;

      break;

    default :

      tradMillions = convertLessThanOneThousand(lesMillions)

        + millions ;

    }

    resultat =  resultat + tradMillions;

 

    String tradCentMille;

    switch (lesCentMille) {

    case 0:

      tradCentMille = ;

      break;

    case 1 :

      tradCentMille = mille ;

      break;

    default :

      tradCentMille = convertLessThanOneThousand(lesCentMille)

        + mille ;

    }

    resultat =  resultat + tradCentMille;

 

    String tradMille;

    tradMille = convertLessThanOneThousand(lesMille);

    resultat =  resultat + tradMille;

 

    return resultat;

  }

 

  public static void main(String[] args) {

    System.out.println(*** + FrenchNumberToWords.convert(0));

    System.out.println(*** + FrenchNumberToWords.convert(9));

    System.out.println(*** + FrenchNumberToWords.convert(19));

    System.out.println(*** + FrenchNumberToWords.convert(21));

    System.out.println(*** + FrenchNumberToWords.convert(28));

    System.out.println(*** + FrenchNumberToWords.convert(71));

    System.out.println(*** + FrenchNumberToWords.convert(72));

    System.out.println(*** + FrenchNumberToWords.convert(80));

    System.out.println(*** + FrenchNumberToWords.convert(81));

    System.out.println(*** + FrenchNumberToWords.convert(89));

    System.out.println(*** + FrenchNumberToWords.convert(90));

    System.out.println(*** + FrenchNumberToWords.convert(91));

    System.out.println(*** + FrenchNumberToWords.convert(97));

    System.out.println(*** + FrenchNumberToWords.convert(100));

    System.out.println(*** + FrenchNumberToWords.convert(101));

    System.out.println(*** + FrenchNumberToWords.convert(110));

    System.out.println(*** + FrenchNumberToWords.convert(120));

    System.out.println(*** + FrenchNumberToWords.convert(200));

    System.out.println(*** + FrenchNumberToWords.convert(201));

    System.out.println(*** + FrenchNumberToWords.convert(232));

    System.out.println(*** + FrenchNumberToWords.convert(999));

    System.out.println(*** + FrenchNumberToWords.convert(1000));

    System.out.println(*** + FrenchNumberToWords.convert(1001));

    System.out.println(*** + FrenchNumberToWords.convert(10000));

    System.out.println(*** + FrenchNumberToWords.convert(10001));

    System.out.println(*** + FrenchNumberToWords.convert(100000));

    System.out.println(*** + FrenchNumberToWords.convert(2000000));

    System.out.println(*** + FrenchNumberToWords.convert(3000000000L));

    System.out.println(*** + FrenchNumberToWords.convert(2147483647));

    /*

    *** OUTPUT

    *** zéro

    *** neuf

    *** dix-neuf

    *** vingt et un

    *** vingt-huit

    *** soixante et onze

    *** soixante-douze

    *** quatre-vingt

    *** quatre-vingt-un

    *** quatre-vingt-neuf

    *** quatre-vingt-dix

    *** quatre-vingt-onze

    *** quatre-vingt-dix-sept

    *** cent

    *** cent un

    *** cent dix

    *** cent vingt

    *** deux cents

    *** deux cent un

    *** deux cent trente-deux

    *** neuf cent quatre-vingt-dix-neuf

    *** mille

    *** mille un

    *** dix mille

    *** dix mille un

    *** cent mille

    *** deux millions

    *** trois milliards

    *** deux milliards cent quarante-sept millions

    **          quatre cent quatre-vingt-trois mille six cent quarante-sept

    */

  }

}

You can handle dollar and cent conversion by calling the convert method two times.

String phrase = 12345.67 ;

Float num = new Float( phrase ) ;

int dollars = (int)Math.floor( num ) ;

int cent = (int)Math.floor( ( num - dollars ) * 100.0f ) ;

 

String s = $ + EnglishNumberToWords.convert( dollars ) + and

          + EnglishNumberToWords.convert( cent ) + cents ;

Another way to use a built-in function of your DBMS (if available). For Oracle

SQL> select to_char(to_date(873,'J'), 'JSP') as converted_form from dual;

 

CONVERTED_FORM

---------------------------

EIGHT HUNDRED SEVENTY-THREE

 

SQL>

'JSP' means :

J : the Julian format.

SP : spells the word for the number passed to to_date

Solution courtesy of: Jigar Joshi

Discussion

Because you cannot have a general algorithm for every locale, no. You have to implement your own algorithm for every locale that you are supporting.

** EDIT **

Just for the heck of it, I played around until I got this class. It cannot display Long.MIN_VALUE because of bit restrictions... but I presume it could be modified and change long value types to double for decimal or even bigger numbers It can display any numbers up to 66 digits and 26 decimals using a string representation of the number. You may add more ScaleUnit for more decimals...

/**

* This class will convert numeric values into an english representation

*

* For units, see : http://www.jimloy.com/math/billion.htm

*

* @author yanick.rochon@gmail.com

*/

public class NumberToWords {

 

    static public class ScaleUnit {

        private int exponent;

        private String[] names;

        private ScaleUnit(int exponent, String...names) {

            this.exponent = exponent;

            this.names = names;

        }

        public int getExponent() {

            return exponent;

        }

        public String getName(int index) {

            return names[index];

        }

    }

 

    /**

    * See http://www.wordiq.com/definition/Names_of_large_numbers

    */

    static private ScaleUnit[] SCALE_UNITS = new ScaleUnit[] {

        new ScaleUnit(63, vigintillion, decilliard),

        new ScaleUnit(60, novemdecillion, decillion),

        new ScaleUnit(57, octodecillion, nonilliard),

        new ScaleUnit(54, septendecillion, nonillion),

        new ScaleUnit(51, sexdecillion, octilliard),

        new ScaleUnit(48, quindecillion, octillion),

        new ScaleUnit(45, quattuordecillion, septilliard),

        new ScaleUnit(42, tredecillion, septillion),

        new ScaleUnit(39, duodecillion, sextilliard),

        new ScaleUnit(36, undecillion, sextillion),

        new ScaleUnit(33, decillion, quintilliard),

        new ScaleUnit(30, nonillion, quintillion),

        new ScaleUnit(27, octillion, quadrilliard),

        new ScaleUnit(24, septillion, quadrillion),

        new ScaleUnit(21, sextillion, trilliard),

        new ScaleUnit(18, quintillion, trillion),

        new ScaleUnit(15, quadrillion, billiard),

        new ScaleUnit(12, trillion, billion),

        new ScaleUnit(9, billion, milliard),

        new ScaleUnit(6, million, million),

        new ScaleUnit(3, thousand, thousand),

        new ScaleUnit(2, hundred, hundred),

        //new ScaleUnit(1, ten, ten),

        //new ScaleUnit(0, one, one),

        new ScaleUnit(-1, tenth, tenth),

        new ScaleUnit(-2, hundredth, hundredth),

        new ScaleUnit(-3, thousandth, thousandth),

        new ScaleUnit(-4, ten-thousandth, ten-thousandth),

        new ScaleUnit(-5, hundred-thousandth, hundred-thousandth),

        new ScaleUnit(-6, millionth, millionth),

        new ScaleUnit(-7, ten-millionth, ten-millionth),

        new ScaleUnit(-8, hundred-millionth, hundred-millionth),

        new ScaleUnit(-9, billionth, milliardth),

        new ScaleUnit(-10, ten-billionth, ten-milliardth),

        new ScaleUnit(-11, hundred-billionth, hundred-milliardth),

        new ScaleUnit(-12, trillionth, billionth),

        new ScaleUnit(-13, ten-trillionth, ten-billionth),

        new ScaleUnit(-14, hundred-trillionth, hundred-billionth),

        new ScaleUnit(-15, quadrillionth, billiardth),

        new ScaleUnit(-16, ten-quadrillionth, ten-billiardth),

        new ScaleUnit(-17, hundred-quadrillionth, hundred-billiardth),

        new ScaleUnit(-18, quintillionth, trillionth),

        new ScaleUnit(-19, ten-quintillionth, ten-trillionth),

        new ScaleUnit(-20, hundred-quintillionth, hundred-trillionth),

        new ScaleUnit(-21, sextillionth, trilliardth),

        new ScaleUnit(-22, ten-sextillionth, ten-trilliardth),

        new ScaleUnit(-23, hundred-sextillionth, hundred-trilliardth),

        new ScaleUnit(-24, septillionth,quadrillionth),

        new ScaleUnit(-25, ten-septillionth,ten-quadrillionth),

        new ScaleUnit(-26, hundred-septillionth,hundred-quadrillionth),

    };

 

    static public enum Scale {

        SHORT,

        LONG;

 

        public String getName(int exponent) {

            for (ScaleUnit unit : SCALE_UNITS) {

                if (unit.getExponent() == exponent) {

                    return unit.getName(this.ordinal());

                }

            }

            return ;

        }

    }

 

    /**

    * Change this scale to support American and modern British value (short scale)

    * or Traditional British value (long scale)

    */

    static public Scale SCALE = Scale.SHORT;

 

 

    static abstract public class AbstractProcessor {

 

        static protected final String SEPARATOR = ;

        static protected final int NO_VALUE = -1;

 

        protected List getDigits(long value) {

            ArrayList digits = new ArrayList();

            if (value == 0) {

                digits.add(0);

            } else {

                while (value > 0) {

                    digits.add(0, (int) value % 10);

                    value /= 10;

                }

            }

            return digits;

        }

 

        public String getName(long value) {

            return getName(Long.toString(value));

        }

 

        public String getName(double value) {

            return getName(Double.toString(value));

        }

 

        abstract public String getName(String value);

    }

 

    static public class UnitProcessor extends AbstractProcessor {

 

        static private final String[] TOKENS = new String[] {

            one, two, three, four, five, six, seven, eight, nine,

            ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen

        };

 

        @Override

        public String getName(String value) {

            StringBuilder buffer = new StringBuilder();

 

            int offset = NO_VALUE;

            int number;

            if (value.length() > 3) {

                number = Integer.valueOf(value.substring(value.length() - 3), 10);

            } else {

                number = Integer.valueOf(value, 10);

            }

            number %= 100;

            if (number < 10) {

                offset = (number % 10) - 1;

                //number /= 10;

            } else if (number < 20) {

                offset = (number % 20) - 1;

                //number /= 100;

            }

 

            if (offset != NO_VALUE && offset < TOKENS.length) {

                buffer.append(TOKENS[offset]);

            }

 

            return buffer.toString();

        }

 

    }

 

    static public class TensProcessor extends AbstractProcessor {

 

        static private final String[] TOKENS = new String[] {

            twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety

        };

 

        static private final String UNION_SEPARATOR = -;

 

        private UnitProcessor unitProcessor = new UnitProcessor();

 

        @Override

        public String getName(String value) {

            StringBuilder buffer = new StringBuilder();

            boolean tensFound = false;

 

            int number;

            if (value.length() > 3) {

                number = Integer.valueOf(value.substring(value.length() - 3), 10);

            } else {

                number = Integer.valueOf(value, 10);

            }

            number %= 100;  // keep only two digits

            if (number >= 20) {

                buffer.append(TOKENS[(number / 10) - 2]);

                number %= 10;

                tensFound = true;

            } else {

                number %= 20;

            }

 

            if (number != 0) {

                if (tensFound) {

                    buffer.append(UNION_SEPARATOR);

                }

                buffer.append(unitProcessor.getName(number));

            }

 

            return buffer.toString();

        }

    }

 

    static public class HundredProcessor extends AbstractProcessor {

 

        private int EXPONENT = 2;

 

        private UnitProcessor unitProcessor = new UnitProcessor();

        private TensProcessor tensProcessor = new TensProcessor();

 

        @Override

        public String getName(String value) {

            StringBuilder buffer = new StringBuilder();

 

            int number;

            if (value.isEmpty()) {

                number = 0;

            } else if (value.length() > 4) {

                number = Integer.valueOf(value.substring(value.length() - 4), 10);

            } else {

                number = Integer.valueOf(value, 10);

            }

            number %= 1000;  // keep at least three digits

 

            if (number >= 100) {

                buffer.append(unitProcessor.getName(number / 100));

                buffer.append(SEPARATOR);

                buffer.append(SCALE.getName(EXPONENT));

            }

 

            String tensName = tensProcessor.getName(number % 100);

 

            if (!tensName.isEmpty() && (number >= 100)) {

                buffer.append(SEPARATOR);

            }

            buffer.append(tensName);

 

            return buffer.toString();

        }

    }

 

    static public class CompositeBigProcessor extends AbstractProcessor {

 

        private HundredProcessor hundredProcessor = new HundredProcessor();

        private AbstractProcessor lowProcessor;

        private int exponent;

 

        public CompositeBigProcessor(int exponent) {

            if (exponent <= 3) {

                lowProcessor = hundredProcessor;

            } else {

                lowProcessor = new CompositeBigProcessor(exponent - 3);

            }

            this.exponent = exponent;

        }

 

        public String getToken() {

            return SCALE.getName(getPartDivider());

        }

 

        protected AbstractProcessor getHighProcessor() {

            return hundredProcessor;

        }

 

        protected AbstractProcessor getLowProcessor() {

            return lowProcessor;

        }

 

        public int getPartDivider() {

            return exponent;

        }

 

        @Override

        public String getName(String value) {

            StringBuilder buffer = new StringBuilder();

 

            String high, low;

            if (value.length() < getPartDivider()) {

                high = ;

                low = value;

            } else {

Enjoying the preview?
Page 1 of 1