ArrayList<Type> arrL = new ArrayList<Type>();
Here Type is the data type of elements in ArrayList
to be created
LinkedList<Type> linkL = new LinkedList<Type>();
Here Type is the data type of elements in LinkedList
to be created
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
ArrayList
LinkedList
ArrayList internally uses dynamic array to store the elements.
LinkedList internally uses doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory
Manipulation with LinkedList is faster than ArrayList because it uses Doubly Linked List so no bit shifting is required in memory
ArrayList class can act as a list only because it implements List only
LinkedList class can act as a list and queue both because it implements List and Deque interfaces
ArrayList is better for storing and accessing data
LinkedList is better for manipulating data
Insertions are easy and fast in LinkedList as compared to ArrayList because there is no risk of resizing array and copying content to new array if array gets full which makes adding into ArrayList of O(n) in worst case, while adding is O(1) operation in LinkedList in Java. ArrayList also needs to be update its index if you insert something anywhere except at the end of array.
Removal also better in LinkedList than ArrayList due to same reasons as insertion.
LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.
Both LinkedList and ArrayList require O(n) time to find if an element is present or not. However we can do Binary Search on ArrayList if it is sorted and therefore can search in O(Log n) time.
remove an element from ArrayList
using remove() method
using Iterator.remove() method
using remove() method
ArrayList provides two overloaded remove() method.
remove(int index) : Accept index of object to be removed.
remove(Obejct obj) : Accept object to be removed.
// Java program to demonstrate working of remove
// on an integer arraylist
import java.util.List;
import java.util.ArrayList;
public class GFG
{
public static void main(String[] args)
{
List al = new ArrayList();
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// This makes a call to remove(int) and
// removes element 20.
al.remove(1);
// Now element 30 is moved one position back
// So element 30 is removed this time
al.remove(1);
System.out.println("Modified ArrayList : " + al);
}
}
Output :
Modified ArrayList : [10, 1, 2]
We can see that the passed parameter is considered as index. How to remove elements by value.
// Java program to demonstrate working of remove
// on an integer arraylist
import java.util.List;
import java.util.ArrayList;
public class GFG
{
public static void main(String[] args)
{
List al = new ArrayList();
al.add(10);
al.add(20);
al.add(30);
al.add(1);
al.add(2);
// This makes a call to remove(Object) and
// removes element 1
al.remove(new Integer(1));
// This makes a call to remove(Object) and
// removes element 2
al.remove(new Integer(2));
System.out.println("Modified ArrayList : " + al);
}
}
Output :
Modified ArrayList : [10, 20, 30]
Check whether a string is not null and not empty
String.isEmpty():
public boolean isEmpty()
Returns true if, and only if, length() is 0.
Returns:
true if length() is 0, otherwise false
Be sure to use the parts of&&in this order, because java will not proceed to evaluate the second part if the first part of&&fails, thus ensuring you will not get a null pointer exception fromstr.isEmpty()ifstris null.
Beware, it's only available since Java SE 1.6. You have to checkstr.length() == 0on previous versions.
if(str != null && !str.isEmpty())
To ignore whitespace as well:
if(str != null && !str.trim().isEmpty())
Aside:
String.trim():
public String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
If this String object represents an empty character sequence, or the first and last characters of character
sequence represented by this String object both have codes greater than '\u0020' (the space character), then
a reference to this String object is returned.
Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object
representing an empty string is created and returned.
Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and
let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object
is created, representing the substring of this string that begins with the character at index k and ends with
the character at index m-that is, the result of this.substring(k, m+1).
This method may be used to trim whitespace (as defined above) from the beginning and end of a string.
Returns:
A copy of this string with leading and trailing white space removed, or this string if it has no leading
or trailing white space.
String.toCharArray()
The java String.toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string.
Syntax:
public char[] toCharArray()
Return : It returns a newly allocated character array.
Example:
public class CharArrayExample{
public static void main(String args[]){
String str = new String("Welcome to BeginnersBook.com");
char[] array= str.toCharArray();
System.out.print("Content of Array:");
for(char c: array){
System.out.print(c);
}
}
}
Output:
Content of Array:Welcome to BeginnersBook.com
String.valueOf()
This method has the following variants, which depend on the passed parameters. This method returns the String representation of the passed argument.
valueOf(boolean b) − Returns the string representation of the boolean argument.
valueOf(char c) − Returns the string representation of the char argument.
valueOf(char[] data) − Returns the string representation of the char array argument.
valueOf(char[] data, int offset, int count) − Returns the string representation of a specific subarray of the char array argument.
valueOf(double d) − Returns the string representation of the double argument.
valueOf(float f) − Returns the string representation of the float argument.
valueOf(int i) − Returns the string representation of the int argument.
valueOf(long l) − Returns the string representation of the long argument.
valueOf(Object obj) − Returns the string representation of the Object argument.
Example:
import java.io.*;
public class Test {
public static void main(String args[]) {
double d = 102939939.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };
System.out.println("Return Value : " + String.valueOf(d) );
System.out.println("Return Value : " + String.valueOf(b) );
System.out.println("Return Value : " + String.valueOf(l) );
System.out.println("Return Value : " + String.valueOf(arr) );
}
}
Output:
Return Value : 1.02939939939E8
Return Value : true
Return Value : 1232874
Return Value : abcdefg
String.valueOf() vs. Object.toString()
According to the Java documentation, String.valueOf() returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So there shouldn't really be a difference except for an additional method invocation.
Also, in the case of Object.toString(), if the instance is null, a NullPointerException will be thrown, so arguably, it's less safe.
public static void main(String args[]) {
String str = null;
System.out.println(String.valueOf(str)); // This will print a String equal to "null"
System.out.println(str.toString()); // This will throw a NullPointerException
}
Map.entrySet()
The entrySet()method is used to get a Set view of the mappings contained in this map. The method call returns a set view of the mappings contained in this map.
Example:
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
// create hash map
HashMap newmap = new HashMap();
// populate hash map
newmap.put(1, "tutorials");
newmap.put(2, "point");
newmap.put(3, "is best");
// create set view for the map
Set set = newmap.entrySet();
// check set values
System.out.println("Set values: " + set);
}
}
Output:
Set values: [1=tutorials, 2=point, 3=is best]
Map.Entryis a key and its value combined into one class. This allows you to iterate overMap.entrySet()instead of having to iterate overMap.keySet(), then getting the value for each key. A better way to write what you have is:
for (Map.Entry<String, JButton> entry : listbouton.entrySet()) {
String key = entry.getKey();
JButton value = entry.getValue();
this.add(value);
}
ArrayList.addAll()
boolean addAll(Collection c):
This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress(implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty).
Parameters:
c : This is the collection containing elements to be added to this list.
Exception:
NullPointerException : If the specified collection is null
Example:
// Java program to illustrate
// boolean addAll(Collection c)
import java.io.*;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String args[])
{
// create an empty array list1 with initial
// capacity as 5
ArrayList<Integer> arrlist1 =
new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist1.add(12);
arrlist1.add(20);
arrlist1.add(45);
// prints all the elements available in list1
System.out.println("Printing list1:");
for (Integer number : arrlist1)
System.out.println("Number = " + number);
// create an empty array list2 with an initial
// capacity
ArrayList<Integer> arrlist2 =
new ArrayList<Integer>(5);
// use add() method to add elements in list2
arrlist2.add(25);
arrlist2.add(30);
arrlist2.add(31);
arrlist2.add(35);
// let us print all the elements available in
// list2
System.out.println("Printing list2:");
for (Integer number : arrlist2)
System.out.println("Number = " + number);
// inserting all elements, list2 will get printed
// after list1
arrlist1.addAll(arrlist2);
System.out.println("Printing all the elements");
// let us print all the elements available in
// list1
for (Integer number : arrlist1)
System.out.println("Number = " + number);
}
}
Output:
Output:Printing list1:
Number = 12
Number = 20
Number = 45
Printing list2:
Number = 25
Number = 30
Number = 31
Number = 35
Printing all the elements
Number = 12
Number = 20
Number = 45
Number = 25
Number = 30
Number = 31
Number = 35
boolean addAll(int index, Collection c):
This method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection’s iterator.
Parameters:
index : The index at which to insert the first element from the specified collection.
c : This is the collection containing elements to be added to this list.
Exception:
IndexOutOfBoundsException : If the index is out of range
NullPointerException : If the specified collection is null
Example:
// Java program to illustrate
// boolean addAll(int index, Collection c)
import java.io.*;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String args[])
{
// create an empty array list1 with initial
// capacity 5
ArrayList<Integer> arrlist =
new ArrayList<Integer>(5);
// using add() method to add elements in the
// list
arrlist.add(12);
arrlist.add(20);
arrlist.add(45);
// prints all the elements available in list1
System.out.println("Printing list1:");
for (Integer number : arrlist)
System.out.println("Number = " + number);
// create an empty array list2 with an initial
// capacity
ArrayList<Integer> arrlist2 =
new ArrayList<Integer>(5);
// use add() method to add elements in list2
arrlist2.add(25);
arrlist2.add(30);
arrlist2.add(31);
arrlist2.add(35);
// prints all the elements available in list2
System.out.println("Printing list2:");
for (Integer number : arrlist2)
System.out.println("Number = " + number);
// inserting all elements of list2 at third
// position
arrlist.addAll(2, arrlist2);
System.out.println("Printing all the elements");
// prints all the elements available in list1
for (Integer number : arrlist)
System.out.println("Number = " + number);
}
}
Output:
Output:Printing list1:
Number = 12
Number = 20
Number = 45
Printing list2:
Number = 25
Number = 30
Number = 31
Number = 35
Printing all the elements
Number = 12
Number = 20
Number = 25
Number = 30
Number = 31
Number = 35
Number = 45
References
GeeksforGeeks
Stack Overflow
tutorialspoint
: Implemented with the concept of dynamic array.
: Implemented with the concept of doubly linked list.