Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 12

http://www.electronics-tutorials.ws/sequential/seq_1.

html

http://phppot.com/php/mysql-blob-using-php/

https://www.youtube.com/watch?v=-fLtTRYQX0M&index=6&list=PLdFoBaBes4baoAa-
eTRJ1FVPR2CGglUsF

http://www.kean.edu/~ocisweb/downloads/FrontPage_2003/

WFDWY-XQXJF-RHRYG-BG7RQ-BBDHM

The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays
are of a fixed length. After arrays are created, they cannot grow or shrink, which
means that you must know in advance how many elements an array will hold. But,
sometimes, you may not know until run time precisely how large of an array you
need. To handle this situation, the collections framework defines ArrayList. In
essence, an ArrayList is a variable-length array of object references. That is, an
ArrayList can dynamically increase or decrease in size. Array lists are created
with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array may be shrunk.

ArrayList has the constructors shown here:

ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)

The first constructor builds an empty array list. The second constructor builds an
array list that is initialized with the elements of the collection c. The third
constructor builds an array list that has the specified initial capacity. The
capacity is the size of the underlying array that is used to store the elements.
The capacity grows automatically as elements are added to an array list.

The following program shows a simple use of ArrayList. An array list is created,
and then objects of type String are added to it. (Recall that a quoted string is
translated into a String object.) The list is then displayed. Some of the elements
are removed and the list is displayed again.

// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}
The output from this program is shown here:

Initial size of al: 0


Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Notice that a1 starts out empty and grows as elements are added to it. When
elements are removed, its size is reduced.

Although the capacity of an ArrayList object increases automatically as objects are


stored in it, you can increase the capacity of an ArrayList object manually by
calling ensureCapacity( ). You might want to do this if you know in advance that
you will be storing many more items in the collection that it can currently hold.
By increasing its capacity once, at the start, you can prevent several
reallocations later. Because reallocations are costly in terms of time, preventing
unnecessary ones improves performance. The signature for ensureCapacity( ) is shown
here:

void ensureCapacity(int cap)

Here, cap is the new capacity. Conversely, if you want to reduce the size of the
array that underlies an ArrayList object so that it is precisely as large as the
number of items that it is currently holding, call
trimToSize( ), shown here:

void trimToSize( )
Obtaining an Array from an ArrayList

When working with ArrayList, you will sometimes want to obtain an actual array that
contains the contents of the list. As explained earlier, you can do this by calling
toArray( ). Several reasons exist why you might want to convert a collection into
an array such as:

• To obtain faster processing times for certain operations.


• To pass an array to a method that is not overloaded to accept a collection.
• To integrate your newer, collection-based code with legacy code that does not
understand collections.

Whatever the reason, converting an ArrayList to an array is a trivial matter, as


the following program shows:

// get array
Object ia[] = al.toArray();
int sum = 0;
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}
The output from the program is shown here:

Contents of al: [1, 2, 3, 4]


Sum is: 10
The program begins by creating a collection of integers. As explained, you cannot
store primitive types in a collection, so objects of type Integer are created and
stored. Next, toArray( ) is called and it obtains an array of Objects. The contents
of this array are cast to Integer, and then the values are summed.

How to overload methods ?

Solution
This example displays the way of overloading a method depending on type and number
of parameters.

class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new House that is " + i + " feet tall");
height = i;
}
void info() {
System.out.println("House is " + height + " feet tall");
}
void info(String s) {
System.out.println(s + ": House is " + height + " feet tall");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(0);
t.info();
t.info("overloaded method");

//Overloaded constructor:
new MyClass();
}
}
Result
The above code sample will produce the following result.

Building new House that is 0 feet tall.


House is 0 feet tall.
Overloaded method: House is 0 feet tall.
bricks
The following is an another sample example of Method Overloading

public class Calculation {


void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


Calculation cal = new Calculation();
cal.sum(20,30,60);
cal.sum(20,20);
}
}
The above code sample will produce the following result.

110
40

==========
How to use method overloading for printing different types of array ?

Solution
This example displays the way of using overloaded method for printing types of
array (integer, double and character).

public class MainClass {


public static void printArray(Integer[] inputArray) {
for (Integer element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Double[] inputArray) {
for (Double element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Character[] inputArray) {
for (Character element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void main(String args[]) {
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");


printArray(integerArray);

System.out.println("\nArray doubleArray contains:");


printArray(doubleArray);

System.out.println("\nArray characterArray contains:");


printArray(characterArray);
}
}
Result
The above code sample will produce the following result.

Array integerArray contains:


1
2
3
4
5
6

Array doubleArray contains:


1.1
2.2
3.3
4.4
5.5
6.6
7.7

Array characterArray contains:


H
E
L
L
O

How to compare two strings ?

Solution
Following example compares two strings by using str compareTo (string), str
compareToIgnoreCase(String) and str compareTo(object string) of string class and
returns the ascii difference of first odd characters of compared strings.

public class StringCompareEmp{


public static void main(String args[]){
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;

System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
}

String compare by equals()


This method compares this string to the specified object. The result is true if and
only if the argument is not null and is a String object that represents the same
sequence of characters as this object.

public class StringCompareequl{


public static void main(String []args){
String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
}
}
The above code sample will produce the following result.

true

false
String compare by == operator
public class StringCompareequl{
public static void main(String []args){
String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
}
}
The above code sample will produce the following result.

true

false

==
How to split a string into a number of substrings ?

Solution
Following example splits a string into a number of substrings with the help of str
split(string) method and then prints the substrings.

public class JavaStringSplitEmp{


public static void main(String args[]) {
String str = "jan-feb-march";
String[] temp;
String delimeter = "-";
temp = str.split(delimeter);

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


System.out.println(temp[i]);
System.out.println("");
str = "jan.feb.march";
delimeter = "\\.";
temp = str.split(delimeter);
}
for(int i =0; i < temp.length; i++) {
System.out.println(temp[i]);
System.out.println("");
temp = str.split(delimeter,2);

for(int j = 0; j < temp.length; j++){


System.out.println(temp[j]);
}
}
}
}
Result
The above code sample will produce the following result.
jan

feb

march

jan

jan
feb.march
feb.march

jan
feb.march
This is another example of string split

public class HelloWorld {


public static void main(String args[]) {
String s1 = "t u t o r i a l s";
String[] words = s1.split("\\s");
for(String w:words) {
System.out.println(w);
}
}
}
Result
The above code sample will produce the following result.

t
u
t
o
r
i
a
l
s

===========

How to determine the Unicode code point in string ?

Solution
This example shows you how to use codePointBefore() method to return the character
(Unicode code point) before the specified index.

public class StringUniCode {


public static void main(String[] args) {
String test_string = "Welcome to TutorialsPoint";
System.out.println("String under test is = "+test_string);

System.out.println("Unicode code point at"


+" position 5 in the string is = "
+ test_string.codePointBefore(5));
}
}

=======
How to buffer strings ?
Solution
Following example buffers strings and flushes it by using emit() method.

public class StringBuffer {


public static void main(String[] args) {
countTo_N_Improved();
}
private final static int MAX_LENGTH = 30;
private static String buffer = "";

private static void emit(String nextChunk) {


if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
System.out.println(buffer);
buffer = "";
}
buffer += nextChunk;
}
private static final int N = 100;
private static void countTo_N_Improved() {
for (int count = 2; count<= N; count = count+2) {
emit(" " + count);
}
}
}
======
How to optimize string concatenation ?

Solution
Following example shows performance of concatenation by using "+" operator and
StringBuffer.append() method.

public class StringConcatenate {


public static void main(String[] args) {
long startTime = System.currentTimeMillis();

for(int i = 0;i<5000;i++) {
String result = "This is"
+ "testing the"
+ "difference"+ "between"
+ "String"+ "and"+ "StringBuffer";
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken for string"
+ "concatenation using + operator : "
+ (endTime - startTime)+ " ms");
long startTime1 = System.currentTimeMillis();

for(int i = 0;i<5000;i++) {
StringBuffer result = new StringBuffer();
result.append("This is");
result.append("testing the");
result.append("difference");
result.append("between");
result.append("String");
result.append("and");
result.append("StringBuffer");
}
long endTime1 = System.currentTimeMillis();
System.out.println("Time taken for String concatenation"
+ "using StringBuffer : "
+ (endTime1 - startTime1)+ " ms");
}
}
=========

How to sort an array and search an element inside it?

Solution
Following example shows how to use sort () and binarySearch () method to accomplish
the task. The user defined method printArray () is used to display the output:

import java.util.Arrays;

public class MainClass {


public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 @ " + index);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");

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


if(i != 0) {
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
}

Linear Search
Following example shows search array element with Linear Search.

public class HelloWorld {


public static void main(String[] args) {
int[] a = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
int target = 0;

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


if (a[i] == target) {
System.out.println("Element found at index " + i);
break;
}
}
}
}

Bubble Sort
Following example shows sort array element with Bubble Sort.

public class HelloWorld {


static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i = 0; i < n; i++) {
for(int j=1; j < (n-i); j++) {
if(arr[j-1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
System.out.println("Array Before Bubble Sort");

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


System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);
System.out.println("Array After Bubble Sort");

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


System.out.print(arr[i] + " ");
}
}
}

How to sort an array and insert an element inside it?

Solution
Following example shows how to use sort () method and user defined method
insertElement ()to accomplish the task.

import java.util.Arrays;

public class MainClass {


public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);

int index = Arrays.binarySearch(array, 1);


System.out.println("Didn't find 1 @ " + index);

int newIndex = -index - 1;


array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if (i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[], int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index + 1, length - index);
return destination;
}
}

How to determine the upper bound of a two dimensional array ?

Solution
Following example helps to determine the upper bound of a two dimensional array
with the use of arrayname.length.

public class Main {


public static void main(String args[]) {
String[][] data = new String[2][5];
System.out.println("Dimension 1: " + data.length);
System.out.println("Dimension 2: " + data[0].length);
}
}
The above code sample will produce the following result.

Dimension 1: 2
Dimension 2: 5

How to search the minimum and the maximum element in an array ?

Solution
This example shows how to search the minimum and maximum element in an array by
using Collection.max() and Collection.min() methods of Collection class .

import java.util.Arrays;
import java.util.Collections;

public class Main {


public static void main(String[] args) {
Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));

System.out.println("Min number: " + min);


System.out.println("Max number: " + max);
}
}

How to merge two arrays ?

Solution
This example shows how to merge two arrays into a single array by the use of
list.Addall(array1.asList(array2) method of List class and Arrays.toString ()
method of Array class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {


public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
}
}

You might also like