List to Array of Primitive Conversion

Written by admin on . Posted in Core Java

package com.list;

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

/*
 * Here we will learn to convert List to Arrays.
 */
public class ListToArrayType {

	/*
	 * Note*: Here in this code Autoboxing is done also generics is getting used. Because of generics 
	 * 	      Casting is not required. 
	 */

	public static void main(String[] args) {
		List list = new ArrayList();
		
		list.add(1);
		list.add(2);
		list.add(3);
		
		System.out.println("Values in List-");
		
		for(int str: list)
		{
			System.out.println(str);
		}
		
		System.out.println("Converting list in Arrays");
		
		Integer[] strArr = list.toArray(new Integer[0]);
		
		System.out.println("Values in String arrays");
		
		for(int str : strArr)
			System.out.println(str);
		
	}
}

String Split whitespace example

Written by admin on . Posted in Core Java


package com.string;

import java.util.Scanner;

/*
 * Here we will learn to split the string based on whitespace.
 */
public class StringSplitWhiteSpace {

	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the string to split.");
		String strToSplit = scanner.nextLine();

		/*
		 * Whitespace Character contains 
		 * 1- \t
		 * 2- \n
		 * 3- \f
		 * 4- \r
		 * 
		 * In combination whitespace can be represented by \s
		 * 
		 * Note* : Here s is SMALL.
		 */

		System.out.println("Complete String : " + strToSplit);
		System.out.println("String after split");

		String strArr[] = strToSplit.split("\\s");

		for (String str : strArr)
			System.out.println(str);
	}

}

List collection tutorial for Java Beginners

Written by admin on . Posted in Core Java

Here we will learn about the List interface and different implementation of it in details. List Interface which is in java.util package is a subtype of java.util.Collection Interface.

List Interface Salient Point

  1. It is a part of java.util package.
  2. It is a subtype of java.util.Collection Interface
  3. List is an Ordered Collection. Means
    elements of
    List can be accessed in ordered way (By index).
  4. Allows Duplicate values.
  5. Allows NULL values.
  6. List has a special Iterator named ListIterator.

Concrete Implementation of List Interface

  • java.util.ArrayList
  • java.util.LinkedList
  • java.util.Vector
  • java.util.Stack

Create List Instance

List listA = new ArrayList();

List listB = new LinkedList();

List listC = new Vector();

List listD = new Stack();

Adding Element in List

List listA = new ArrayList();

 

listA.add("element 1");

listA.add("element 2");

listA.add("element 3");

 

listA.add(0, "element 0");

Accessing Element in List

 

Removing Element in List