Some of the new features added in Java 5
Generic:
While declaring collection objects you can specify the type of objects the collection can hold. We have the following advantages
1. You don’t have to worry about accidentally putting a different object in the collection which will result in runtime ClassCastException, as the compiler will detect those while compiling the code.
2. While getting an object from the collection, you don’t have to typecast to the class.
Sample code:
HashMap<String, Country> countryMap = new HashMap<String, Country> (); countryMap.put("US", new Country("US","United States Of America","Washington")); countryMap.put("IN", new Country("IN","India","Delhi")); //... some code here............. // now get country by country code Country usa = countryMap.get("US"); /* Note: No need to typecast to class here as in java 1.4 */Enhanced Looping:
Let’s understand from the code sampleHashMap<String, Country> countryMap = new HashMap<String, Country>(); countryMap.put("US", new Country("US","United States Of America","Washington")); countryMap.put("IN", new Country("IN","India","Delhi")); //... some code here............. // Iterate through each country // Code in 1.4 Collection countryList = countryMap.values(); for( Iterator countryIte = countryList.iterator();countryIte.hasNext();){ Country country = (Country)countryIte.next(); System.out.print("Country :" + country.getName() + " Capital :" + country.getCapital()); } // Code in 1.5 for (Country country : countryMap.values()){ System.out.print("Country :" + country.getName() + " Capital :" + country.getCapital()); } Similarly you can use it in array. // Returns the sum of the elements of a int sum(int[] a) { int result = 0; for (int i : a) result += i; return result; }Autoboxing:
In java 1.4, if you have to put primitive type to Collection, you need to wrap that primitive to corresponding wrapper class. For example, if you want to put int key and value to HashMap,
you have to code as follows.HashMap employeeMap = new HashMap(); employeeMap.put(new Integer(empId), new Employee("Name");In java 1.5 same code you can write as
HashMap<Integer,Employee> employeeMap = new HashMap<Integer,Employee>(); // put employee employeeMap.put(empId, new Employee("Name")); // no need to wrap empId in Integer // get employee Employee emp = employeeMap.get(empId);Note: It’s important to note that the Key will be added as Integer to HashMap, but now it’s done by JVM, so there is some performance cost. If your code is performance-critical, then it’s a good idea to wrap primitive type to its corresponding wrapper classes.