Showing posts with label java - ArrayList. Show all posts
Showing posts with label java - ArrayList. Show all posts

Wednesday, November 29, 2017

JAVA - How to use ArrayList

Class java.util.ArrayList is very useful class for storing objects. It is replacement for Vector class. ArrayList supports null values and duplicates.
/* -- ArrayList creating  */

ArrayList ar = new ArrayList();

/* -- add items */

ar.add( "One" );
ar.add( "Two" );
ar.add( "Two" );
ar.add( null );
ar.add( "Three" );
ar.add( null );

/* -- get and write second item */

System.out.println( ar.get( 1 ).toString() );

/* -- write all items */

System.out.println( ar.toString() );
Output is:
Two
[One, Two, Two, null, Three, null]

JAVA - How restart java application

public void restartApplication() throws URISyntaxException, IOException
{
  /* where is java and local app ? */    

  final String javaBin = System.getProperty( "java.home" ) + File.separator + 
                         "bin" + File.separator + "java";
  final File currentJar = new File( getClass().getProtectionDomain().getCodeSource()
                          .getLocation().toURI() );

  /* is it a jar file ? */

  if( !currentJar.getName().endsWith(".jar") ) return;

  /* build command: java -jar application.jar */

  final ArrayList command = new ArrayList();
  command.add( javaBin );
  command.add( "-jar" ); command.add( currentJar.getPath() );

  /* run it - and close current */

  final ProcessBuilder builder = new ProcessBuilder( command );
  builder.start();
  System.exit(0);
}