ArrayList or LinkedList, which is faster?

Tags

, , , , , ,

Discrete Mathematical Algorithm, and Data Structures

Discrete Mathematical Algorithm, and Data Structures

https://leanpub.com/discretemathematicalalgorithmanddatastructures

Which is faster? ArrayList, or LinkedList?

It’s not a million dollar question. We all know that LinkedList is faster. But, do you know the reason.

Here is an explanation.

As we have seen that the two most natural ways of storing sequences in computer memory are arrays and linked lists. ArrayList is an ADT that uses all concepts of handling Arrays with more flexibility. That is why, the time complexity is same for the both.

In LinkedList, it does not work that way. We usually model the memory as a sequence of memory cells, each of which has a unique address. An array or ArrayList is a contiguous piece of memory. Each cell of the memory stores one object, which is a part of the sequence stored in an Array or an ArrayList.

In a singly LinkedList two successive memory cells are allocated for each object of the sequence. Two memory cells form a node of a sequence. The first cell stores the object and the second cell stores a reference to the next node of the list.

In the next node there is two memory cells, and the previous node points to the first memory cell of the next node.

In a doubly linked list, the mechanism changes. Then we not only store a reference to the successor of each element, but we need to have a reference to its predecessor. It means each node should have three successive memory cells. We will discuss it in detail later.

At present, we will see how a singly LinkedList works.

 

//code 
package fun.sanjibsinha.nodepackage;

public class NodeClass {

private int dataElement;
private NodeClass next;

public NodeClass(){
dataElement = 0;
next = null;
}

public NodeClass(int dataInt){
this.dataElement = dataInt;
this.next = null;
}

public NodeClass(int dataElement, NodeClass node){
this.dataElement = dataElement;
this.next = node;
}

public void insertAfter(NodeClass node){
NodeClass temporaryNode = this.next;
this.next = node;
node.next = temporaryNode;
}

public NodeClass nextNode(){
return this.next;
}

public void displayDataElement(){
System.out.println(this.dataElement);
}

}


package fun.sanjibsinha.nodepackage;

public class DisplayLinkedList {

public static void main(String[] args) {

NodeClass headNode;
NodeClass nextNodeOne;
NodeClass nextNodeTwo;
NodeClass nextNodeThree;
NodeClass currentNode;

headNode = new NodeClass(10);

nextNodeOne = new NodeClass(120);
headNode.insertAfter(nextNodeOne);

nextNodeTwo = new NodeClass(1200);
nextNodeOne.insertAfter(nextNodeTwo);

nextNodeThree = new NodeClass(12000);
nextNodeTwo.insertAfter(nextNodeThree);

currentNode = headNode;
while (currentNode != null){
currentNode.displayDataElement();
currentNode = currentNode.nextNode();
}
}
}

 

In the above code we have implemented the ADT of a singly LinkedList, where we have only added or inserted next node until it reaches the NULL value.

 

//output
10
120
1200
12000

 

At the same time we can see a code sample of ArrayList where we have added a few elements. Before moving further, we need to know that ArrayList is an ADT that provides a generic class, which has many useful methods to deal with a collection of data. It also supports different data types. Using the ArrayList methods we could easily add, remove, modify any element. Moreover, we could count the size of the list and based on which we could use the looping construct.

An ArrayList is declared as follows:

ArrayList<T> arrayList = new ArrayList<T>();

Here T is the data type, not the primitive data type, but the Wrapper Class. Let us take a look at some implementations.

//code
//Java
package fun.sanjibsinha;

import java.util.ArrayList;

public class ArrayListExamples {

public static void main(String[] args) {

/**
* ArrayList examples
* ArrayList is an ADT that provides a generic class, which has many useful methods to deal
* with a collection of data. It also supports different data types.
* An ArrayList is declared as follows:
* ArrayList<T> arrayList = new ArrayList<T>();
* Here T is the data type.
*/
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("index");
arrayList.add("about");
arrayList.add("contact");
arrayList.add("products");
arrayList.add("sellers");

for (int i = 0; i < arrayList.size(); i++){
System.out.println(arrayList.get(i));
}
}
}

 

We have added a few elements and the output is quite simple.

 

//output of code 6.3
index
about
contact
products
sellers

It always takes more time to add elements to any ArrayList. Specially when we remove any element midway.

 

Duck number example in Java

Tags

, , ,

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

https://leanpub.com/javaintensivecodingbootcamplearnlanguagebasicsandalgorithm

In Mathematics, the Duck number is defined as a number which has zeroes present in it. However, not in the beginning of the number. For example 3210, 7056 are Duck numbers. But not 0321, or 0756.

//code to find a duck number
package fun.sanjibsinha;

//check whether a number is Duck Number or not.

import java.util.Scanner;

class DuckNumber{

public int checkingDuck(String num){

int len = num.length();
int countZero = 0 ;
char myChar;

for(int i = 1; i < len; i++)
{
myChar = num.charAt(i);
if(myChar == '0')
countZero++;
}
return countZero ;
}
}

public class ProblemEightyTwo
{
static int num = 0;
static String str;
static char digitAtIndexZero;

public static void main(String[] args){
DuckNumber myDuck = new DuckNumber();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check whether the number is a Duck number or not: ");
num = sc.nextInt();
String num1 = Integer.toString(num);
str = Integer.toString(num);
digitAtIndexZero = str.charAt(0);
if( myDuck.checkingDuck(str) > 0 && digitAtIndexZero != '0')
System.out.println("It is a duck number");
else
System.out.println("It is not a duck number");
}
}



We are taking inputs from the users to examine the nature of the number.

Let us check the output as follows:

//output
Enter a number to check whether the number is a Duck number or not: 
123
It is not a duck number
Enter a number to check whether the number is a Duck number or not: 
1023
It is a duck number

Armstrong number example

Tags

, , , ,

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

https://leanpub.com/javaintensivecodingbootcamplearnlanguagebasicsandalgorithm

Finding the Armstrong number in a given range is rather a code heavy experience. Before that we should know what is Armstrong number, what it exactly means in number theory. It is also known as a narcissistic number, because it is the sum of its own digits each raised to the power of the number of digits.

Consider the number 153. The number of digits is 3. Now, if each digit of that number is raised to the power of 3, the sum is equal to 153.
Keeping that logic in mind, from 0 to 9, all numbers are Armstrong or narcissistic number.

In the following program, we will let users to give a lower limit and an upper limit, such as, 0 as lower limit, and 100, or 1000 as upper limit. Our program will find all the Armstrong numbers between 0 to that number.

Continue reading

Palindromic Prime or Pal Prime

Tags

, ,

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

https://leanpub.com/javaintensivecodingbootcamplearnlanguagebasicsandalgorithm

‘Palindromic Prime’ or in short ‘Pal Prime’ is a number, which is simultaneously palindrome and prime. It is not necessary that every palindromic number should be prime. Consider 22. It is palindromic, but not prime. It has factors more than 2.

Now prime is a number where factors will be only 1 and that number, like 11. The number 11 is divisible by only 1 and that number 11. Furthermore it is palindromic. If you place the number in reverse order, it will read the same.

In this program, we will test whether the number is palindromic and prime both.

Continue reading

Introduction Data Structures and Algorithm

Tags

, , , ,

discrete-mathematical-algorithm-data-structures

discrete-mathematical-algorithm-data-structures

https://leanpub.com/discretemathematicalalgorithmanddatastructures

We have already been introduced to data structures before. Of course, we have learned a few operations using Array in various languages, so we can say that the concept of data structures is not completely alien to us.
We need a good way to store, organize and use our data. As times passes by, the nature of data is becoming not only more and more complex, but also it’s getting bigger in quantity. More and more people are getting hooked to the Internet, exchanging huge amount of data every day, in various forms; scientific data are getting larger, we need weather data to be processed to get more accurate weather prediction, medical data are becoming humongous; this list is endless.
Therefore, we need more efficient way to sort, organize, and use that data.
Data Structures are all about this. It has a very close relation with Algorithm, because managing such huge amount of data is less tedious if we have more efficient Algorithm, ready at our hand.While managing such huge humongous data, by sorting, organizing, or using them, one is not only prone to error, but also fail to satisfy one of the most important requirements – time and space. Yes, time complexity really matters, so the space.

Continue reading

Twisted Prime in Java

Tags

, , ,

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

JAVA CODING BOOTCAMP: LEARN LANGUAGE BASICS AND ALGORITHM

Java Coding Bootcamp for Beginners

 

It is one of the most common problem we face in any IT job interview related to software industry or any programming language. Can you write a program that will determine whether a number is twisted prime or not? Let us try it in Java. You can apply the same algorithm in other language like C, C++, PHP, C#, Python or Dart. First of all let us know what is twisted prime number. It is a prime number whose reverse is also a prime number, such as, 11, 71, 13, etc. Therefore, when the reversed prime number is also prime, we call it twisted prime. Example is 97. The reverse of 97 is 79, which is also prime.

Continue reading

PHP 7: How API, Connector, driver and extension work together

Tags

, , , , , , , , , ,

https://leanpub.com/u/sanjibsinha

An Application Programming Interface or API, classifies the classes, methods, functions and variables that one application will need to call in order to tasks. APIs can be procedural or object oriented. The procedural API helps you to call functions to carry out tasks. And the object-oriented API creates class instantiation and then calls methods on resulting objects. The object-oriented API is much preferable as they lead to better organized code.
The connector is a piece of software that allows your applications to connect to the MySQL database server. MySQL provides connectors for variety of languages including PHP. In a dynamic database driven web applications, you need to write php code to perform a few tasks including connecting to the database server, querying the database and other database related functions. The Connector is a kind of software that allows your application to connect to a database server.
Continue reading

Java: Why we need Interface in Java

Tags

, , ,

https://leanpub.com/u/sanjibsinha

A class can be extended and at the same time, it may implement multiple interfaces. The next problem is a showcase for the same example.

package fun.sanjibsinha;
/*
class cannot extend multiple classes
so we cannot write like this: public class CatyClass extends MobileClass, MobileFeatures
 */
public class CatyClass extends MobileClass implements MobileUpgradable {

    private double batteryStrength = 0.0;
    private int pixel = 10;
    private double mins = 60.0;
    private int days = 0;
    public double version = 1.0;

    public double getVersion() {
        return version;
    }

    public void setVersion(double version) {
        this.version = version;
    }

    public double getBatteryStrength() {
        return batteryStrength;
    }
    public void setBatteryStrength(double batteryStrength) {
        this.batteryStrength = batteryStrength;
    }

    public double getMins() {
        return mins;
    }
    public void setMins(double mins) {
        this.mins = mins;
    }

    public double takeCharge(double mins){
        this.mins = mins;
        return mins;
    }
    public double batteryCanLast(int days){
        this.days = days;
        return days;
    }

    public CatyClass(){}
    public CatyClass(String name, String color, double price, double mins){
        super(name, color, price);
        this.mins = mins;
    }

}

After the class declaration, we need an interface.

Continue reading

Data Structures in Java

Tags

, ,

https://leanpub.com/u/sanjibsinha

 

How we could manage a collection of data in Java? There are many options, different type of data structures.

You have already seen array. However, array has many limitations, such as it holds fixed number of values of a single type. You cannot change it.
To overcome such limitations, Java introduces core collection interfaces. They encapsulate different type of collections. You have learned the role of an interface, it is actually a contract. So it allows collections to be manipulated independently. The foundation of Java Collections Framework consists of such Core Collection Interfaces.
They are ‘Set’, ‘List’, ‘Queue’, ‘Deque’, and ‘Map’.
In the last problem, we have seen an example of ‘LinkedList’ class, which is a collection based on a Linked List. As the name suggests, it is a collection of container that holds data and each container has a link identifier that links it either to the next one or the previous one. The last link identifier is always ‘null’, because it points to nothing.

Continue reading

While or Do-While? It depends on your problem

Tags

, , , ,

https://leanpub.com/u/sanjibsinha

In some cases like the previous examples, the ‘while’ loop is indispensable. The user input validation is also done by using ‘while’ loop. We can do it by applying the ‘if-else’ logic. But, that should not be as robust as the code below:

package fun.sanjibsinha.understandingloops;
/**
* how to force the user to give valid input
*/

import java.util.Scanner;

public class WhileThree {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter your age : between 0 and 150 ");
int age = sc.nextInt();
while (age < 0 || age > 150){
System.out.println("That is impossible; try again! ");
age = sc.nextInt();
}
System.out.println("Your are " + age + " years old.");
}
}

 

Continue reading