Showing posts with label conversion. Show all posts
Showing posts with label conversion. Show all posts

Friday, 24 June 2011

Converting a Collection to an array

If you have been using Collections in Java 5 you probably have stumbled upon a problem of converting a given Collection<T> into an array of type T. In the Collection interface, there is a method called toArray() which returns an array of type Object[]. But then, if since Java 5 Collections are using generics, shouldn’t it be possible to get an array T[] of the generic type we used in the declaration of our Collection<T>? Well, there is a method T[] toArray(T[] a). But what is that strange “T[] a” doing there? Why is there no simple method T[] toArray() without any strange parameters? It seams like it shouldn’t be a big problem to implement such a method… but actually it is not possible to do so in Java 5, and we will show here why.
Let’s start from trying to implement that method by ourselves. As an example, we will extend the ArrayList class and implement there a method T[] toArrayT(). The method simply uses the standard Object[] toArray() method and casts the result to T[].

import java.util.*;

/**
 * Implementation of the List interface with "T[] toArrayT()" method.
 * In a normal situation you should never extend ArrayList like this !
 * We are doing it here only for the sake of simplicity.
 * @param <T> Type of stored data
 */
class HasToArrayT<T> extends ArrayList<T> {
public T[] toArrayT() {
return (T[]) toArray();
}
}

public class Main {
public static void main(String[] args) {
// We create an instance of our class and add an Integer
HasToArrayT<Integer> list = new HasToArrayT<Integer>();
list.add(new Integer(4));

// We have no problems using the Object[] toArray method
Object[] array = list.toArray();
System.out.println(array[0]);

// Here we try to use our new method... but fail on runtime
Integer[] arrayT = list.toArrayT(); // Exception is thrown :
// "Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer"
System.out.println(arrayT[0]);
}
}

If you compile it and run, it will throw an exception when trying to use our new method. But why? Didn’t we do everything right? Objects stored in the array ARE Integers and toArray method returns an array of those objects, so what is the problem?

Java compiler gives us a hint to understand what is wrong. During compilation, you should see a warning at line 12, saying something like “Type safety: Unchecked cast from Object[] to T[]“. Let’s follow this trace and check if the array that comes out of our toArrayT method is really of type Integer[]. Put this code somewhere in main() method before the Integer[] arrayT = list.toArrayT() line :

System.out.println("toArrayT() returns Integer[] : "
+ (list.toArrayT() instanceof Integer[]));

When you run the program, you should get “false”, which means that toArrayT() DID NOT return Integer[]. Why? Well, many of you probably know the answer – it is Type Erasure. Basically, during compilation the compiler removes every information about the generic types. Effectively, when the program runs, all the appearances of T in our HasToArrayT class are nothing more than simple Object’s. It means, that the cast in the function toArrayT does not cast to Integer[] any more, even if we are using Integer in the declaration of the generic type. Actually, there is also a second problem here, coming from the way Java handles casting of arrays. This time however we would like to concentrate just on the first one – usage of generics.
So, if the information that T is an Integer is no longer there at runtime, is there any way to really return an array of type Integer[] ? Yes, there is, and it is exactly what the method T[] toArray(T[] a) in the Collections framework is doing. But the price you have to pay for it is the additional argument a, whose instance you have to create first by yourself. How do they use it there? Let’s look at how it is really implemented in, for example, ArrayList :

public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}

As it is explained in the method’s Javadoc, if the specified array a is big enough it just copies elements into this array. If not, it creates a new array. What is important for us, is that when creating a new array it uses Arrays.copyOf method, specifying there a.getClass() as the type of array to create. So that’s where it needs that additional argument – to know what type of array to create. But then you might say, would it not be easier to fit there T.class instead of a.getClass()? No. Because of type erasure, T is no longer the type we specified. Moreover, we would get a compile time error if we wrote T.class! Some of you may be thinking about creating a new array the simple way – new T[], but it is also not possible because of the same reason. We have already discussed how to get Generic Arrays in Java here.
To put it straight, in order to return a new array of T, the type that we really specified, we MUST give something of that type to the function toArray. There is no other way the function could now what type of array it should create, because the generic type T supplied when creating that Collection is erased every time during compilation.
One other way to implement such a method is by using the Class<T[]> type as an input parameter. This way, instead of having to create a new instance a of array T[] and then using it in the function toArray(a), we could use the .class field – toArrayT(TYPE[].class) :

public T[] toArrayT(Class<T[]> c) {
return (T[]) Arrays.copyOf(toArray(), size(), c);
}

It still takes an argument, but it has two advantages over the T[] toArray(T[] a) function. First, it does not require you to create an instance of an array just to pass it to the function. Second, it is simpler. Of course, it has still the disadvantage of having to pass some argument.

After all, there is no perfect way to perform such a conversion. The best solution would be not to use arrays at all. Code with arrays is difficult to maintain and invites people to make mistakes that often come out not earlier than on runtime. Using collections is generally much preferred and if you use them all the time, you will not be forced to deal with the toArray method.

Wednesday, 22 June 2011

String utility function : Converting int[] to String

Method 1 - Writing our own function

public static String toString(int[] intArray) {

String separator =
",";

StringBuilder sb =
new StringBuilder("");

if (intArray != null && intArray.length > 0) {

for (int i = 0; i < intArray.length; i++) {

sb.append(intArray[i]);

if (i < (intArray.length - 1)) {

sb.append(separator);

}

}

}

return sb.toString();

}

Method2 - Using Arrays.asList()
Arrays.asList(intArray).toString()

Tuesday, 14 June 2011

How to convert map to List in java?

Assuming map is your instance of Map :
map.values() will return a Collection containing all of the map's values
map.keys() will return a Set containing all of the map's keys
map.entrySet() will return a Set containing all map key value pairs.

Get list of keys

List<String> list = new ArrayList<String>(map.keySet());

Get list of values

List<String> list = new ArrayList<String>(map.values());

Saturday, 30 April 2011

How to convert a String array to ArrayList?

Method 1:

String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);


Method 2:


List<String> list = new ArrayList<String>(words.length);
for (String s : words) {
list.add(s);
}



Method 3 :


Collections.addAll(myList, myStringArray);


Note: In the method no 1 Arrays.asList() is efficient because it doesn't need to copy the content of the array. This method returns a List that is a "view" onto the array - a wrapper that makes the array look like a list. When you change an element in the list, the element in the original array is also changed. Note that the list is fixed size - if you try to add elements to the list, you'll get an exception.



If you only need read access to the array as if it is a List and you don't want to add or remove elements from the list, then only use method no 1.

Friday, 15 April 2011

Convert ArrayList to Arrays in Java and vice-versa

ArrayList class has a method called toArray() that we are using in our example to convert it into Arrays.
Following is simple code snippet that converts an array list of countries into string array.

List<String> countryList= new ArrayList<String>();

countryList.add("India");
countryList.add("Switzerland");
countryList.add("Italy");
countryList.add("France");

String [] countries = list.toArray(new String[countryList.size()]);

So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.

List<T> list = new ArrayList<T>();

T [] countries = list.toArray(new T[list.size()]);

Convert Array to ArrayList

We just saw how to convert ArrayList in Java to Arrays. But how to do the reverse? Well, following is the small code snippet that converts an Array to ArrayList:

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

...

String[] countries = {"India", "Switzerland", "Italy", "France"};
List list = new Arrays(Arrays.asList(countries));
System.out.println("ArrayList of Countries:" + list);

Monday, 11 April 2011

Convert Exponential form to Decimal number format in Java

While working with Doubles and Long numbers in Java you will see that most of the value are displayed in Exponential form.
For example : In following we are multiplying 2.35 with 10000 and the result is printed.
//Division example
Double a = 2.85d / 10000;
System.out.println("1) " + a.doubleValue());
 
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2) " + a.doubleValue());
Result:
1)  2.85E-4
2) 2.85E8
Thus you can see the result is printed in exponential format. Now you may want to display the result in pure decimal format like: 0.000285 or 285000000. You can do this simply by using class java.math.BigDecimal. In following example we are using BigDecimal.valueOf() to convert the Double value to BigDecimal and than .toPlainString() to convert it into plain decimal string.
import java.math.BigDecimal;
//..
//..
 
//Division example
Double a = 2.85d / 10000;
System.out.println("1) " + BigDecimal.valueOf(a).toPlainString());
 
//Multiplication example
a = 2.85d * 100000000;
System.out.println("2) " + BigDecimal.valueOf(a).toPlainString());
Result:
1)  0.000285
2) 285000000
The only disadvantage of the above method is that it generates lonnnnggg strings of number. You may want to restrict the value and round off the number to 5 or 6 decimal point. For this you can use java.text.DecimalFormat class. In following example we are rounding off the number to 4 decimal point and printing the output.
import java.text.DecimalFormat;
//..
//..
 
Double a = 2.85d / 10000;
DecimalFormat formatter = new DecimalFormat("0.0000");
System.out.println(formatter .format(a));
Result:
0.0003

Thursday, 31 March 2011

Conversion from decimal to binary

You can convert a decimal to binary using toBinaryString() method of Integer wrapper class as follows.

int i = 42;
String binstr = Integer.toBinaryString(i);

Conversion from integer to hexadecimal and vice-versa

You can convert a hexadecimal to integer using two different methods as shown below:
int i = Integer.valueOf("B8DA3"16).intValue();

   or

int i = Integer.parseInt("B8DA3"16);  


You can convert a decimal to binary using three different methods as shown below:

int i = 42;
String hexstr = Integer.toString(i, 16);

or

String hexstr = Integer.toHexString(i);

or (with leading zeroes and uppercase)

public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}

Conversion from primitive types to String and vice-versa

Conversion to String
Converting from primitive type to String can be done by using wrapper classes's static toString method.
Eg.
double i = 42.0;
String str = Double.toString(i);


Case of ascii format to string:
You can convert an ASCII code to String using toString() method of Character wrapper class as shown below:
 int i = 64;
 String aChar = new Character((char)i).toString();


Conversion from string:
Then in this case use parseWrapper method. Example:
For float :

String s = "31.2";
float f = Float.parseFloat(s);

Sunday, 20 March 2011

Convert String to byte array

This example shows how to do it:

String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";

byte[] theByteArray = stringToConvert.getBytes();

Convert from byte array to string

This the function to convert byte array to string:

//eg. byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
public static String convertByteArrayToString(byte[] byteArray) {

String value = new String(byteArray);

return value;
}

Sunday, 13 March 2011

How to Convert an ArrayList to a HashSet?

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayListToHashSet {

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add(null);
list.add("A");
list.add("B");
Set<String> hashset = new HashSet<String>(list);
list = new ArrayList<String>(hashset);
System.out.println(list.toString());
}
}

The above code example also can be used to remove duplicate items from an ArrayList.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ArrayListToHashSet {

public static void main(String[] args) {
List list = new ArrayList();
list.add(null);
list.add("A");
list.add("A");
list.add("A");
list.add("A");
list.add("B");
list.add("B");
list.add("B");
list.add("C");
Set hashset = new HashSet(list);
list = new ArrayList(hashset);
System.out.println(list.toString());
}

}

Friday, 11 March 2011

Calculating difference between 2 dates

Again to do Date arithematic we need Calender class.

Following function takes 2 dates and prints difference in days, millis etc...you can make you own function to return long etc...

public static void printDiff(Date dat1, Date dat2)
{
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

// Set the date for both of the calendar instance
cal1.setTime(dat1);
cal2.setTime(dat2);

// Get the represented date in milliseconds
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();

// Calculate difference in milliseconds
long diff = milis2 - milis1;

// Calculate difference in seconds
long diffSeconds = diff / 1000;

// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);

// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);

// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}

Sunday, 28 November 2010

How do I convert String to Date object?

The following code shows how we can convert a string representation of date into java.util.Date object.
To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public Date StringToDate
{
         DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

       try
        {
            Date today = df.parse("20/12/2005");           
           System.out.println("Today = " + df.format(today));
      } catch (ParseException e)
      {
            System.out.println("Cannot convert to date "+e);
        }
    
}
And here is the result of our code:
Today = 20/12/2005
The example starts by creating an instance of SimpleDateFormat with "dd/MM/yyyy" format which mean that the date string is formatted in day-month-year sequence.
Finally using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.
Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.
Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800

Wednesday, 27 October 2010

Convert string to enum

public enum Shape { RECTANGLE, CIRCLE, LINE } 
The valueOf() method can be used to convert a string value to an enum value. Here is an example of reading in a Shape value from a Scanner object in.
drawing = Shape.valueOf(in.next());
or
drawing = Shape.valueOf("RECTANGLE") 
We can have custom methods to deal with this, if we dont want to have some extra customization.
eg. If the text is not the same to the enumeration value:
public enum Blah {
  A
("text1"),
  B
("text2"),
  C
("text3"),
  D
("text4");

 
private String text;

 
Blah(String text) {
   
this.text = text;
 
}

 
public String getText() {
   
return this.text;
 
}

 
public static Blah fromString(String text) {
   
if (text != null) {
     
for (Blah b : Blah.values()) {
       
if (text.equalsIgnoreCase(b.text)) {
         
return b;
     
}
   
}
   
return null;
 
}
}

toString() for Enums

public enum Shape { RECTANGLE, CIRCLE, LINE }
Shape drawing = Shape.RECTANGLE;   // Only a Shape value can be assigned.
System.out.println(drawing);    // Prints RECTANGLE

Override toString method for All Enums
A semicolon after the last element is required to be able to compile it. More details on overriding enum toString method can be found.
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.

@Override public String toString() {
//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}


Override toString method element by element
The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},

TWO {
public String toString() {
return "this is two";
}
}
}
Running the following test code will produce this:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
-------------
this is one
this is two
Another interesting fact is, once you override toString() method, you in effect turn each element into an anonymous inner class. So after compiling the above enum class, you will see a long list of class files:
MyType.class
MyType$1.class
MyType$2.class

Monday, 2 August 2010

Converting an integer to binary string - Binary.java


/*************************************************************************
* Compilation: javac Binary.java
* Execution: java Binary n
*
* Prints out n in binary.
*
* % java Binary 5
* 101
*
* % java Binary 106
* 1101010
*
* % java Binary 0
* 0
*
* % java Binary 16
* 10000
*
* Limitations
* -----------
* Does not handle negative integers.
*
* Remarks
* -------
* could use Integer.toBinaryString(N) instead.
*
*************************************************************************/

public class Binary {
public static void main(String[] args) {

// read in the command-line argument
int n = Integer.parseInt(args[0]);

// set v to the largest power of two that is <= n
int v = 1;
while (v <= n/2) {
v = v * 2;
}

// check for presence of powers of 2 in n, from largest to smallest
while (v > 0) {

// v is not present in n
if (n < v) {
System.out.print(0);
}

// v is present in n, so remove v from n
else {
System.out.print(1);
n = n - v;
}

// next smallest power of 2
v = v / 2;
}

System.out.println();

}

}

Though written a program, we can use inbuilt lib of java - See here.