How to create our own linked list in Java

Each node is an object of class. Node can store an int, and a reference to next Node object. Also note that you can use a complex object, as a member instead of an int.

As shown in the example, next reference of last element is null.

while loop is used to iterate thru the elements in the linked list.
Also, more methods can be added which performs adding an element, deleting an element, etc….

Below is a Program of singly linked list in Java.

class Node
{
	private int i;
	
	Node next;

	Node(int i)
	{
		this.i = i;
	}
	public void set(int i)
	{
		this.i = i;
	}
	
	public int get()
	{
		return i;
	}
	
}

public class OwnLinkedList {
	public static void main(String args[])
	{
	//create elements, and assign next element
	Node n1 = new Node(10);
		
	Node n2 = new Node(20);
	n1.next = n2;
		
	Node n3 = new Node(30);
	n2.next = n3;
		
	Node n4 = new Node(40);
	n3.next = n4;
		
	Node n5 = new Node(50);
	n4.next = n5;
	n5.next = null;
		
	Node tmp = n1;
	while(tmp.next!=null)
	{
		System.out.println(tmp.get());
		tmp = tmp.next;
	}
		
	}
}

double linked list
double linked list

Below is program on how to implement double linked list. Advantage of doubly linked list is it can be traversed in both the directions, unlike singly linked list. As shown below, each Node1 has reference to previous element, along with reference to next element. previous reference for first element is null. next reference for last element is null.

class Node1
{
	private int i;
	
	Node1 next;
	Node1 previous;

	Node1(int i)
	{
		this.i = i;
	}
	public void set(int i)
	{
		this.i = i;
	}
	
	public int get()
	{
		return i;
	}
	
}

public class OwnDLinkedList {
	public static void main(String args[])
	{
		//create elements, and assign next and previous element
		Node1 n1 = new Node1(10);
		
		n1.previous = null;
		Node1 n2 = new Node1(20);
		n1.next = n2;
		n2.previous = n1;
		
		Node1 n3 = new Node1(30);
		n2.next = n3;
		n3.previous = n2;
		
		Node1 n4 = new Node1(40);
		n3.next = n4;
		n4.previous = n3;
		
		Node1 n5 = new Node1(50);
		n4.next = n5;
		n5.previous = n4;
		n5.next = null;
		
		Node1 tmp = n1;
		while(tmp.next!=null)
		{
			System.out.println(tmp.get());
			tmp = tmp.next;
		}
		
	}
}

What is circular linked list

Below is an implementation of Circular doubly linked list. Here Head node refers to starting node, Tail node refers to last node.

Circular Linked List
Circular Linked List

public class OwnCLinkedList {
	public static void main(String args[])
	{
		Node1 n_head, n_tail;
		//create elements, and assign next and previous element
		Node1 n1 = new Node1(10);
		
		Node1 n5 = new Node1(50);
		
		n_head = n1; //set head node
		n_tail = n5; //set tail node
		
		n1.previous = n5;
		Node1 n2 = new Node1(20);
		n1.next = n2;
		n2.previous = n1;
		
		Node1 n3 = new Node1(30);
		n2.next = n3;
		n3.previous = n2;
		
		Node1 n4 = new Node1(40);
		n3.next = n4;
		n4.previous = n3;
		
		
		n4.next = n5;
		n5.previous = n4;
		n5.next = n1;
		
		Node1 tmp = n_head;
		while(tmp!=n_tail)
		{
			System.out.println(tmp.get());
			tmp = tmp.next;
		}
		
	}
}

We can make above Data structures better useful by providing methods, to add and delete Node,etc…

Similar steps can be followed to build complex data structures such as Graph

You may also like to read:
How Vector and ArrayList differ
List and Set differences
How ArrayList and LinkedList are implemented internally

Similarities and differences between Vector and ArrayList

Similarities between Vector and ArrayList

1. Both are classes in java.util package
2. Both ArrayList and Vector are implemented from java.util.Collection interface.
Both are based on dynamic arrays
3. Collections class static methods can be applied to both Vector and ArrayList
4. Both can store duplicates, and maintains insertion order of elements.

Differences between Vector and ArrayList

ArrayList
Vector
ArrayList is not Synchronized, by default Vector is synchronized
ArrayList implements methods of Collection interface Vector provides other legacy methods, in addition to methods of Collection interface
ArrayList is Faster, as it is not Synchronized Vector is slower, as it is Synchronized
ArrayList is not Legacy class. ArrayList is introduced along with Collection Framework, in Java 1.2 Vector is Legacy class, and exists since initial version of Java. In Java 1.2, Vector has been accommodated in Collection Framework, and its Legacy methods were preserved, as well
When no more room exists to store an added element, size is increased by half of current size In case of Vector size gets increased by the current size

Methods declared in Collection interface

You may also like to read:
When to use List or Set
What are Synchronized Collections

How to use HashSet, to store our own objects
What is Map?

Difference between Collection interface and Collections class

Collection is interface in java.util package.
Collections is a class in java.util package.

java.util.Collection interface is Base interface for List, Set and Map interfaces.

java.util.Collections class has static methods, which perform operations or manipulations on any Collection. Below table shows list of static methods in Collections class.

Hence the purpose of java.util.Collection interface and java.util.Collections class is different.

Method Name Method Description
1 static <T> boolean addAll(Collection<? super T> c, T… elements) adds all elements of a Collection to the collection, with which this method is invoked.
2 static <T> Queue<T> asLifoQueue(Deque<T> deque) This method returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
3 static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) searches the specified list for the specified object using the binary search algorithm.
4 static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) searches the specified list for the specified object using the binary search algorithm.
5 static <T> void copy(List<? super T> dest, List<? extends T> src) copies all of elements from src List into dest List.
6 static boolean disjoint(Collection<?> c1, Collection<?> c2) returns true if the two collections(sent as parameters) have no elements in common.
7 static <T> List<T> emptyList() returns the empty list (immutable).
8 static <K,V> Map>K,V> emptyMap() returns the empty map (immutable).
9 static <T> Set<T> emptySet() returns the empty set (immutable).
10 static <T> Enumeration<T> enumeration(Collection<T> c) returns an enumeration to traverse over the specified collection.
11 static <T> void fill(List<? super T> list, T obj) replaces all elements of the specified list with the specified element(which is sent as second parameter).
12 static int frequency(Collection<?> c, Object o) returns the number of elements in the specified collection equal to the specified object(which is sent as second parameter).
13 static int indexOfSubList(List<?> source, List<?> target) returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
14 static int lastIndexOfSubList(List<?> source, List<?> target) returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
15 static <T> ArrayList<T> list(Enumeration<T> e) returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
16 static <T extends Object & Comparable< super T> >T max(Collection< extends T> coll) returns maximum element of the given collection, according to the natural ordering of its elements.
17 static <T> T max(Collection< extends T> coll, Comparator< super T> comp) returns the maximum element of given collection, according to order induced by specified comparator, passed as object.
18 static <T extends Object & Comparable< super T>>T min(Collection< extends T> coll) returns the minimum element of given collection, according to default natural ordering of its elements.
19 static <T> T min(Collection< extends T> coll, Comparator< super T> comp) returns the minimum element of given collection, according to the order induced by specified comparator, passed as object.
20 static <T> List<T> nCopies(int n, T o) returns an immutable list consisting n copies of the specified object.
21 static Set newSetFromMap(Map<E,Boolean> map) returns a set from the specified map.
22 static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) replaces all occurrences of one specified value in a list with another.
23 static void reverse(List<> list) reverses the order of the elements in the specified list.
24 static <T> Comparator<T> reverseOrder() returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
25 static <T> Comparator<T> reverseOrder(Comparator<T> cmp) returns a comparator that imposes the reverse ordering of the specified comparator.
26 static void rotate(List<> list, int distance) rotates the elements of the specified list by the specified distance.
27 static void shuffle(List<> list) randomly shuffles the elements in the List using a default source of randomness.
28 static void shuffle(List<> list, Random rnd) randomly shuffles the elements in the List using the specified source of randomness.
29 static <T> Set<T> singleton(T o) returns an immutable set containing only the specified object.
30 static <T> List<T> singletonList(T o) returns an immutable list containing only the specified object.
31 static Map<K,V> singletonMap(K key, V value) returns an immutable map, mapping only the specified key to the specified value.
32 static <T extends Comparable< super T>> void sort(List<T> list) sorts the specified list into ascending order, according to the natural ordering of its elements.
33 static <T> void sort(List<T> list, Comparator< super T> c) sorts the specified list according to the order induced by specified comparator object.
34 static void swap(List<> list, int m, int n) swaps the elements at the specified positions in specified list.

35 static <T> Collection<T> synchronizedCollection(Collection<T> c) returns a synchronized (thread-safe) collection backed by the specified collection.
36 static <T> List<T> synchronizedList(List<T> list) returns a synchronized (thread-safe) list backed by the specified list.
37 static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) returns a synchronized (thread-safe) map backed by the specified map.
38 static <T> Set<T> synchronizedSet(Set<T> s) returns a synchronized (thread-safe) set backed by the specified set.
39 static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap m) returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
40 static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) returns a synchronized (thread-safe) sorted set backed by the specified sorted set.
41 static <T> Collection<T> unmodifiableCollection(Collection< extends T> c) returns an unmodifiable view of specified collection.
42 static <T> List<T> unmodifiableList(List< extends T> list) returns an unmodifiable view of specified list.
43 static <K,V> Map<K,V> unmodifiableMap(Map< extends K,? extends V> m) returns an unmodifiable view of the specified map.
44 static <T> Set<T> unmodifiableSet(Set< extends T> s) returns an unmodifiable view of the specified set.
45 static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap returns an unmodifiable view of the specified sorted map.
46 static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) returns an unmodifiable view of the specified sorted set.

Below are methods provided by java.util.Collection interface,

Method Declaration Method Description
1 public boolean add(Object element) inserts an element in this collection.
2 public boolean addAll(Collection c) adds all elements of specified collection to invoking collection. collection elements in the invoking collection.
3 public boolean remove(Object element) deletes a specified element from this collection.
4 public boolean removeAll(Collection c) deletes all elements of invoking collection.
5 public boolean retainAll(Collection c) deletes all elements of invoking collection except the elements in specified collection(as parameter).
6 public int size() returns total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
8 public boolean contains(Object element) is used to search an element.
9 public boolean containsAll(Collection c) is used to search the specified collection in this collection.
10 public Iterator iterator() returns an iterator, to traverse thru elements of Colelction.
11 public Object[] toArray() returns an array of all Collection elements
12 public boolean isEmpty() return true if Collection is empty
13 public boolean equals(Object element) matches two collection.
14 public int hashCode() returns the hashcode number for collection.

You may also like to read:
Difference between Comparator and Comparable
Difference between List and Set
What is a Map
What are synchronized Collection

Java Map, HashMap and TreeMap

A Map is one of the Collection, and Map is an interface extended from Collection interface. Collection is Base interface of all Java Collection.

As briefed in , List and Set based Collection is used to store and retrieve individual elements. But Map is used to store Key and Value pair object. Key and Value can be any objects.

Map has two different implementations HashMap and TreeMap. In HashMap, Keys are stored based on Hashing technique, where as in TreeMap, Keys are stored in ascending order. However order can be changed by using Comparator or Comparable interfaces.

Below is simple example of TreeMap, which uses default natural ordering on keys, to store elements.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class HashMapDemo {

public static void main(String[] args) {

//Map is used to store key:value pairs

HashMap hm = new HashMap();
hm.put("sfdsfds"/*key*/, "nfghgfhfg"/*value*/);
hm.put("qwdfdsfs", "nfghgfhgf");
hm.put("wererwe", "mhjuytuy");
hm.put("qwewewq", "vnfkhfjfk");
hm.put("nvcsdsfh", "wyetrwye");
hm.put("mnxcvbcjx", "werewhwej");
hm.put("msdfksdfhsd", null);

System.out.println("Value of key,wererwe:"+hm.get("wererwe"));

Set s= hm.entrySet();

//Now s is Set having all the Entry

Iterator itr1 = s.iterator();
while(itr1.hasNext())
{
Map.Entry me = (Map.Entry)itr1.next();
System.out.println("Key:"+me.getKey()+" "+"value:"+me.getValue());
}
return;
}
}

Below is TreeMap example, which uses Comparator, to control the order of elements stored.

Steps to change sorting order of TreeMap

1. Write a class, implementing from Comparator interface
2. In above class, implement the method public int compare(), with the comparison logic, return positive, negative or zero accordingly, from the compare() method.
3. When creating object of TreeMap, pass object of class(created in step 1) to constructor of TreeMap.Now whenever you add an element to TreeMap your comparison logic is used, instead of default natural ordering logic.

Using Comparator with TreeMap example

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

//Step 1
class MyComp1 implements Comparator{

//Step 2
public int compare(String str1, String str2) {
    //return str1.compareTo(str2);
    //return str2.compareTo(str1);
    return str1.length()-str2.length();
    }
 }

public class MyTreeMapComparator {
  public static void main(String a[]){
    //the treemap sorts by key
    //Step 3
    TreeMap hm = new TreeMap(new MyComp1());
    //add key-value pair to TreeMap
    hm.put("java", "language");
    hm.put("computer", "machine");
    hm.put("india","country");
    hm.put("mango","fruit");
    hm.put("ajfdshfsf","ksjfhgikure");
    hm.put("rtrjbsjdff", "bvdsufusfs");
    hm.put("gh", "fsfsdfsd");
    hm.put("k", "arg1");
    //System.out.println(hm);

    Set s= hm.entrySet();
	Iterator itr1 = s.iterator();
	while(itr1.hasNext())
	{
	Map.Entry me = (Map.Entry)itr1.next();
	System.out.println("Key:"+me.getKey()+" "+"value:"+me.getValue());
	}
    }
}

TreeMap with Comparable

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

class MyItem implements Comparable{

	private String name;
	private int numbers;

	public MyItem(String name, int numbers) {
	super();
	this.name = name;
	this.numbers = numbers;
	}

	public String getName() {
	return name;
	}
	public void setName(String name) {
	this.name = name;
	}

	public int getnumbers() {
	return numbers;
	}
	public void setnumbers(int numbers) {
	this.numbers = numbers;
	}

	public String toString()
	{
	return " "+name+" "+numbers;
	}

	public int compareTo(MyItem compareItem) {
	int comparenumbers = ((MyItem) compareItem).getnumbers();
	return this.numbers - comparenumbers;
	}
}

public class MyTreeMapComparable {

    public static void main(String a[]){
        TreeSet ts = new TreeSet();

        MyItem it1 = new MyItem("Bread", 52);
        MyItem it2 = new MyItem("Tomato", 31);
        MyItem it3 = new MyItem("Apple", 61);
        MyItem it4 = new MyItem("Sapota", 12);
        MyItem it5 = new MyItem("Pumpkin", 16);

        ts.add(it1);
        ts.add(it2);
        ts.add(it3);
        ts.add(it4);
        ts.add(it5);

        System.out.println(ts);
    }
}

Also note that java.lang.Comparable can as well be used with TreeMap, to take control over sorting order of elements. However, limitations of Comparable interface, will apply here as well.
You may also like to read:
Comparator with TreeSet
Comparator and Comparable differences
How to write Generic class

Internal implementation of ArrayList and LinkedList Collections

ArrayList underlying implementation is based on Traditional Array data structure. Read Arrays in Java , for details on Arrays.

This post focuses on internal working of ArrayList and LinkedList Collections.

java.util.ArrayList class, is internally implemented as array.

What is array data structure?

An Array is a simplest data structure, which stores same type of elements, sequentially in memory.

Static Array
Static Array

Advantage of array

Accessing an element is very fast. Since base address of array is known, the required element which need to be fetched, can be retrieved, just by doing some manipulations on base address.

Disadvantage of array

Adding an element in between or in the beginning is very slow. Reason is, other existing elements need to be moved right by one position, and new element can be added, to the free slot created. This hits performance of program, and hence it is not recommendable to use Arrays for such situations.

java.util.LinkedList class is internally implemented using linked list data structure.

What is linked list data structure

linked list is a data structure, whose elements are not stored sequentially in memory, and are scattered in the memory. As shown in below picture, each node has Element, and reference to next and previous nodes.

what is linked list
linked list data structure

Advantage of link list data structure

An element can be added any where in between, just by changing previous and next references, as shown in below picture. This operation is slow in an array, as briefed above in array section.

Size of linked list can shrink or increase, during run time, based on the requirement.

Disadvantage of link list data structure

To Access an element, all elements need to be traversed, until the specific required element is reached. Hence searching an element is slower.

Another disadvantage of linked list is, there will be wastage of small memory, since each node need to store references to previous and next nodes.

You may also like to read:
Create our own linked list
When to use List and Set
Which are non synchronized Collections?
Generic version HashSet example

Difference between List and Set

Difference between List and Set
List and Set are interfaces and in java.util package.
Base interface for List and Set is java.util.Collection interface.

List can store duplicate object, but Set does not store duplicate objects.

Iterator and ListIterator can be used to traverse thru the elements of List. But only Iterator can be used to
traverse thru the elements of Set.

List stores elements in the same order as they are added. But Set stores the elements in different order, than they are added.

Difference between ListIterator and Iterator

List has two different implementations, ArrayList and LinkedList. ArrayList internal implementation is based on arrays, and LinkedList internal implementation is based on linked list data structure.

Set has two different implementations, HashSet and TreeSet. HashSet internal implementation is based on hashing the elements, TreeSet is based on Red Back Tree data structure.

ArrayList example:


import java.util.*;
public class ArrayListDemo {

	public static void main(String[] args) {

	//List allows duplicate values, stores values in the order given/added
	//Dynamic Arrays, can shrink or increase size dynamically unlike normal arrays
	ArrayList al = new ArrayList();
	al.add("BCD");
	al.add(0, "A1");
	al.add("A2");
	al.add(2, "A3");
	al.add(3, "A4");

	al.add(0, "C1");

	System.out.println("ArrayList is:"+al);

	Iterator itr = al.iterator();
	//using Iterator, we can traverse only in forward direction
	for(;itr.hasNext();)
	{
	String str = (String)itr.next(); //returns Object
	System.out.println(str+" ");
	}

	ListIterator litr = al.listIterator();

	for(;litr.hasNext();)
	{
	String str = (String)litr.next(); //returns Objectr

	//using ListIterator we can traverse backward as well
	//String pstr = (String) litr.previous();

	System.out.println("Next is "+str);
	}

	System.out.println("-------------------------");

	al.remove(2);
	//Getting Array
	Object obj[] = al.toArray();

	for(int i=0;i

output:
ArrayList is:[C1, A1, BCD, A3, A4, A2]
C1
A1
BCD
A3
A4
A2
Next is C1
Next is A1
Next is BCD
Next is A3
Next is A4
Next is A2
-------------------------
C1
A1
A3
A4
A2

HashSet example:


import java.util.*;

public class SetDemo {

public static void main(String args[])
{
//stores unique values only, no guarantee in the order of objects stored
HashSet hs = new HashSet();

hs.add("to");
hs.add("test");
hs.add("random1");
hs.add("string");
hs.add("some");
hs.add("random1");

System.out.println(" :"+hs);

Iterator itr = hs.iterator();

while(itr.hasNext())
{
System.out.println(itr.next());
}

//ListIterator not available for Set

Enumeration enm=Collections.enumeration(hs);

for(;enm.hasMoreElements();)
{
	System.out.println(enm.nextElement());
}

}

}

output:
:[to, test, string, random1, some]
to
test
string
random1
some
to
test
string
random1
some

You may also like to read:
Can a Collection be concurrent
HashSet using Generic class
How many loops are there in Java

What is the difference between Base interface and Nested interface?

What is Base interface, Nested interface?
A Base interface is an interface, which is extended by another interface. Below is an example code snippet

interface Ia
{
public void met1();
public int met2();
}


interface Ib extends Ia
{
public double met3(float p);
}

Also note that an interface can be derived from more than one interface, as shown in below code snippet

interface Id extends Ib, Ic
{
public float met4();
}

Methods inside an interface cannot be declared private or final.
Member variables declared in an interface are static and public, implicitly.
Member variables declared in an interface cannot be declared as private.

A nested interface or inner interface is an interface declared inside another interface or class.

Interface cannot be declared within body of a method, unlike an inner class declared inside method body.

If an interface need to be accessed directly using an interface or class.

Below is an example of the same

interface Ix{
	public int met1();

	//interface Iy cannot be declared as private member, in below statement
	interface Iy{
		public void met2();
	}
}

class Cx{
	private int i;

	interface Iz{
		public float met3();
	}
}

public class InnerInterfaceDemo implements Ix.Iy, Cx.Iz{

	public static void main(String args[])
	{
		Ix.Iy obj = new InnerInterfaceDemo();
		Cx.Iz obj1 = new InnerInterfaceDemo();

		obj.met2();
		obj1.met3();
	}

	public void met2()
	{
		System.out.println("met2() method");
	}

	public float met3()
	{
		System.out.println("met3() method");
		return 1.2f;
	}

}

In java best example for built in interface Entry, java.util.Map.Entry

You may also like to read:
What is inner class?
How to declare a class inside method body?

Difference between Concurrent, Synchronized and non Synchronized Collections

Difference between Synchronized, Concurrent and Non synchronized Java Collection
As known, java.util.Collection is base interface for java.util.Map, java.util.Set and java.util.List
And all implementations of these interfaces ArrayList, LinkedList, HashSet, TreeSet, HashMap and TreeMap are non synchronized , when used as is.

When a Collection is said to be thread safe?

A Collection is said thread safe, when multiple threads can access, update data in single instance of collection, with out causing corruption/loss of data in that Collection.

How to get synchronized version of List, Set or Map?

Collections utility class provides Concurrent version of each Collection by invoking below methods

Set st = Collections.getSynchronizedSet();
List lst = Collections.getSynchormizedList();
Map mp = Collections.getSynchronizedMap();

Non synchronized collections are not thread safe. Where as, both Synchronized and Concurrent Collections are thread safe.

In addition to above, legacy collections like, Hastable, Vector, Properties are also synchronized.

Though above Collections are thread safe, they are not well suitable for Applications which need to be highly Scalable, and to perform time bound operations. The reason is, synchronization is achieved by making all the public methods of the collection “Synchronized”.

As a solution to this Concurrent Collections have been added during Java. The Concurrent Collection implementations provide much higher concurrency while preserving thread safety.

java.util.concurrent package includes a number of additions to the Java Collections Framework.
ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations.
Implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap.
ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches.
An implementation of ConcurrentNavigableMap is ConcurrentSkipListMap, which is a concurrent analog of TreeMap.

Let us see, why synchronized collections cause performance hit, compared to their Concurrent counter parts.
Taking Hashtable and ConcurrentHashMap, as an example. Both of them are thread safe, but consider using them on large number of elements. Hashtable performance would get degraded as the number of elements increase.

But performance of ConcurrentHashMap will not get degraded as the size grows. The reason for this is, underlying implementation of ConcurrentHashMap uses segmentation, i..e it divides entire Collection into multiple segments, and each segment will be locked or unlocked on need basis, so that other threads can simultaneously access other segments which are not locked.

You may also like to read:
Difference between class level, block level and method level synchronization
HashSet Generic class
How to store user defined objects in a collection

Arrays in Java

An array is simple data structure to store same type of elements stored sequentially in memory.

One Dimensional Arrays
Declaration: Below is syntax to declare an one dimensional float array of size 10

float arr[] = new float[10];

Below is an example to reverse an one dimensional array

public class ReverseArray {
public static void main(String args[])
{
	int marks[] = {10,20,30,40,50,60};

	int tmp, n = marks.length;

	for(int i=0;i<n/2;i++)
	{
		tmp = marks[i];
		marks[i] = marks[n-i-1];
		marks[n-i-1] = tmp;
	}

	for(int i=0;i<n;i++)
	{
		System.out.print(marks[i]+" ");
	}
}
}
Output:
60 50 40 30 20 10

Below is an example showing how to store objects in an array

class A2{
	private String city;
	private float temperature;

	public A2(String mycity, float mytemperature)
	{
		city = mycity;
		temperature = mytemperature;
	}

	public String getCity()
	{
		return city;
	}

	public float getTemperature()
	{
		return temperature;
	}
}

public class ArrayDemo {

	public static void main(String[] args) {

	A2 arr[] = new A2[3];

	A2 oa = new A2("Bangalore",34.3f);
	arr[0] = oa;

	arr[1] = new A2("Chennai",36.3f);

	arr[2] = new A2("Mumbai",35.3f);

	for(int i=0;i<arr.length;i++)
	{
		System.out.println(arr[i].getCity()+" "+arr[i].getTemperature());
	}

	}

}

Two or Multi dimensional Arrays
Declaration: Below is syntax to declare two dimensional double array of 5 rows and 10 columns

double darr[][] = new double[5][10];

initialize two dimensional arrays
int abc[][] = {{1,2},{3,4},{5,6}};

abc.length gives number of rows
abc[0].length gives number of columns

You may also like to read:
How to store configuration settings in Java
What is Comparable in Java?
Example of Comparator
What is Generic class, and how it can be used with HashSet

Properties class

The Properties class extends the Hashtable class and implements the Map interface.It represents the persistent set of properties.
Each key and its  value associated with it in the property list is a string.This class has the following constructors:-

public Properties()
public Properties(Properties def)
The first constructor constructs an empty property list with no default values.

The  second constructor will create a empty property with a default def. The property list def is searched if the property key is not found in the original property list.

Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String value) sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String comment) writes the properties in the OutputStream object.
storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating xml document.
public void storeToXML(Writer w, String comment, String encoding) writers the properties in the writer object for generating xml document with specified encoding.


Below example shows how to use Properties class to set key and value pairs, and get the value.

   import    java.io.*;
   import    java.util.*;
   public      class    Test {
   public      static      void    main(String[] args)  throws    Exception{
 Properties p=  new    Properties();
 p.setProperty(“name”,”ravi”);
 p.setProperty(“email”,”ravi@gmail.com”);
 p.getProperty(“name”);
 }
 }


Below example shows how to use Properties class to get configuration values, from a properties file.

   import    java.util.*;
   import    java.io.*;
   public      class    LoadDemo {
   public      static      void    main(String[] args)  throws    Exception{
     FileReader reader=  new    FileReader(“newFile.properties”);

     Properties p=  new    Properties();
     p.load(reader);

     System.out.println(p.getProperty(“username”));
     System.out.println(p.getProperty(“password”));
 }
 }


Below example shows how to use Properties class to set key and value pairs, to a properties file.

 import java.io.*;
 import java.util.*;
 public class PropertiesExample {
           public static void main(String args[]) {
      try {
   Properties std_code = new Properties();

     grades.setProperty(“Bangalore”, “080”);
    grades.setProperty(“Delhi”, “011”);
     grades.setProperty(“Mumbai”, “022”);
    grades.setProperty(“Chennai”, “044”);
    grades.setProperty(“Kolkata”, “033”);

   // Save the grades properties using store() and an output stream
  FileOutputStream out = new FileOutputStream “stdcodes.properties”);
     std_code.store(out, null);
     out.close();

  // load the properties file using load() and an input stream
   FileInputStream in = new FileInputStream(“stdcodes.propertie  std_code.load(in);
   in.close();

    // iterate properties file to get key-value pairs
     for (String key : std_code.stringPropertyNames()) {
     String value = std_code.getProperty(key);
      System.out.println(“The STD code of  ” + key + ” is: ” + value);
                              }

       } catch (IOException eio) {
     System.out.println(eio.getMessage());
      eio.printStackTrace();
                    }
           }
 }


Below example shows how to retrieve and store Configuration properties in a XML file.
NOTE: Below is sample XML file format

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>This is to test</comment>
<entry key="pname1">pval1</entry>
<entry key="pname2">pval</entry>
<entry key="pname3">pval3</entry>
<entry key="pname4">pval4</entry>
</properties>
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.*;

 public class PropertiesloadfromXMLDemo {

    public static void main(String[] args) {
    Properties pro = new Properties();

    // add some properties
    pro.put("pname1", "pval1");
    pro.put("pname2", "pval2");

    try {

    // create a output and input as a xml file
    FileOutputStream fos = new FileOutputStream("abcproperties.xml");
    FileInputStream fis = new FileInputStream("abcproperties.xml");

    // store the properties in the specific xml
    pro.storeToXML(fos, null);

    // load key/values from the xml
    pro.loadFromXML(fis);

    // Now print all the key/values to Standard output
    pro.list(System.out);

    } catch (IOException ex) {
    ex.printStackTrace();
    }

    }
 }