Question
stringlengths 1
113
| Answer
stringlengths 22
6.98k
|
|---|---|
How to convert Java String to float?
|
We can convert String to float in java using
|
Can you provide an example of Java string to float?
|
public class StringToFloatExample{
public static void main(String args[]){
String s="23.6";
float f=Float.parseFloat("23.6");
System.out.println(f);
}}
Output: 23.6
|
How to convert Java float to String?
|
We can convert float to String in java using String.valueOf() and Float.toString() methods.
|
Can you provide an example of Java float to String using String.valueOf()?
|
public class FloatToStringExample1{
public static void main(String args[]){
float f=12.3F;//F is the suffix for float
String s=String.valueOf(f);
System.out.println(s);
}}
Output: 12.3
|
How to convert Java String to double?
|
We can convert String to double in java using Double.parseDouble() method.
|
Can you provide an example of Java String to double?
|
public class StringToDoubleExample{
public static void main(String args[]){
String s="23.6";
double d=Double.parseDouble("23.6");
System.out.println(d);
}}
Output: 23.6
|
How to convert Java double to String?
|
We can convert double to String in java using String.valueOf() and Double.toString() methods.
|
Can you provide an example of Java double to String using String.valueOf()?
|
public class DoubleToStringExample1{
public static void main(String args[]){
double d=12.3;
String s=String.valueOf(d);
System.out.println(s);
}}
Output: 12.3
|
How to convert Java String to charHow?
|
We can convert String to char in java using charAt() method of String class.
Java Convert String to char
The charAt() method returns a single character only. To get all characters, you can use loop.
|
Can you provide an example of Java string to char: charAt() method?
|
public class StringToCharExample1{
public static void main(String args[]){
String s="hello";
char c=s.charAt(0);//returns h
System.out.println("1st character is: "+c);
}}
Output: 1st character is: h
|
How to convert Java char to String?
|
We can convert String to char in java using charAt() method of String class.
Java Convert String to char
The charAt() method returns a single character only. To get all characters, you can use loop.
|
Can you provide an example of Java char to String using String.valueOf() method?
|
public class CharToStringExample1{
public static void main(String args[]){
char c='S';
String s=String.valueOf(c);
System.out.println("String is: "+s);
}}
Output: String is: S
|
How to convert Java String to Object?
|
We can convert String to Object in java with assignment operator. Each class is internally a child class of Object class. So you can assign string to Object directly.
|
Can you provide an example of Java String to Object?
|
public class StringToObjectExample{
public static void main(String args[]){
String s="hello";
Object obj=s;
System.out.println(obj);
}}
Output: hello
|
How to convert Java Object to String?
|
We can convert Object to String in java using toString() method of Object class or String.valueOf(object) method.
|
Can you provide an example of Java Object to String using Converting User-defined class?
|
class Emp{}
public class ObjectToStringExample{
public static void main(String args[]){
Emp e=new Emp();
String s=e.toString();
String s2=String.valueOf(e);
System.out.println(s);
System.out.println(s2);
}}
Output:
|
How to convert Java int to long?
|
We can convert int to long in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly.
|
Can you provide an example of Java int to long?
|
public class IntToLongExample1{
public static void main(String args[]){
int i=200;
long l=i;
System.out.println(l);
}}
|
How to convert Java long to int?
|
We can convert long to int in java using typecasting. To convert higher data type into lower, we need to perform typecasting.
Typecasting in java is performed through typecast operator (datatype).
Here, we are going to learn how to convert long primitive type into int and Long object into int.
|
Can you provide an example of Java long to int?
|
public class LongToIntExample2{
public static void main(String args[]){
Long l= new Long(10);
int i=l.intValue();
System.out.println(i);
}}
Output:
|
How to convert Java int to double?
|
We can convert int to double in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly.
|
Can you provide an example of Java int to double?
|
public class IntToDoubleExample1{
public static void main(String args[]){
int i=200;
double d=i;
System.out.println(d);
}}
Output:
|
How to convert Java double to int?
|
We can convert double to int in java using typecasting. To convert double data type into int, we need to perform typecasting.
|
Can you provide an example of Java double to int: Typecasting?
|
public class DoubleToIntExample1{
public static void main(String args[]){
double d=10.5;
int i=(int)d;
System.out.println(i);
}}
Output:
|
How to convert Java char to int?
|
We can convert char to int in java using various ways. If we direct assign char variable to int, it will return ASCII value of given character.
|
Java char to int Example: Get ASCII value
|
public class CharToIntExample1{
public static void main(String args[]){
char c='a';
char c2='1';
int a=c;
int b=c2;
System.out.println(a);
System.out.println(b);
}}
Output: 97
49
|
How to convert Java int to char?
|
We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable.
|
Can you provide an example of Java int to char?
|
public class IntToCharExample1{
public static void main(String args[]){
int a=65;
char c=(char)a;
System.out.println(a);
}}
Output: A
|
How to convert Java String to boolean?
|
We can convert String to boolean in java using Boolean.parseBoolean(string) method.
To convert String into Boolean object, we can use Boolean.valueOf(string) method which returns instance of Boolean class.
To get boolean true, string must contain "true". Here, case is ignored. So, "true" or "TRUE" will return boolean true. Any other string value except "true" returns boolean false.
|
Can you provide an example of Java String to boolean using Boolean.parseBoolean()?
|
public class StringToBooleanExample{
public static void main(String args[]){
String s1="true";
String s2="TRue";
String s3="ok";
boolean b1=Boolean.parseBoolean(s1);
boolean b2=Boolean.parseBoolean(s2);
boolean b3=Boolean.parseBoolean(s3);
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
}}
Test it Now
Output: true
true
false
|
How to convert Java boolean to String?
|
We can convert boolean to String in java using String.valueOf(boolean) method.
Alternatively, we can use Boolean.toString(boolean) method which also converts boolean into String.
|
Can you provide an example of Java boolean to String using String.valueOf()?
|
public class BooleanToStringExample1{
public static void main(String args[]){
boolean b1=true;
boolean b2=false;
String s1=String.valueOf(b1);
String s2=String.valueOf(b2);
System.out.println(s1);
System.out.println(s2);
}}
Output: true
false
|
How to convert Java Date to Timestamp?
|
We can convert Date to Timestamp in java using constructor of java.sql.Timestamp class.
The constructor of Timestamp class receives long value as an argument. So you need to convert date into long value using getTime() method of java.util.Date class.
You can also format the output of Timestamp using java.text.SimpleDateFormat class.
|
Can you provide an example of Java Date to Timestamp?
|
import java.sql.Timestamp;
import java.util.Date;
public class DateToTimestampExample1 {
public static void main(String args[]){
Date date = new Date();
Timestamp ts=new Timestamp(date.getTime());
System.out.println(ts);
}
}
Output: 2017-11-02 01:59:30.274
|
How to convert Java Timestamp to Date?
|
We can convert Timestamp to Date in java using constructor of java.util.Date class.
The constructor of Date class receives long value as an argument. So, you need to convert Timestamp object into long value using getTime() method of java.sql.Timestamp class.
Let's see the constructor of Date class and signature of getTime() method.
|
Can you provide an example of Java Timestamp to Date?
|
import java.sql.Timestamp;
import java.util.Date;
public class TimestampToDateExample1 {
public static void main(String args[]){
Timestamp ts=new Timestamp(System.currentTimeMillis());
Date date=new Date(ts.getTime());
System.out.println(date);
}
}
Output:
|
How to convert Binary to Decimal?
|
We can convert binary to decimal in java using Integer.parseInt() method or custom logic.
|
How to convert Java Binary to Decimals using Integer.parseInt()?
|
We can convert binary to decimal in java using Integer.parseInt() method or custom logic.
|
How to convert Decimal to Binary?
|
We can convert decimal to binary in java using Integer.toBinaryString() method or custom logic.
|
How to convert Java Decimal to Binary using conversion: Integer.toBinaryString()?
|
The Integer.toBinaryString() method converts decimal to binary string. The signature of toBinaryString() method is given below:
|
How to convert Hexadecimal to Decimal?
|
We can convert hexadecimal to decimal in java using Integer.parseInt() method or custom logic.
|
What is Java Hexadecimal to Decimal conversion: Integer.parseInt()?
|
The Integer.parseInt() method converts string to int with given redix. The signature of parseInt() method is given below:
|
How to convert Java Decimal to Hexadecimal?
|
We can convert decimal to hexadecimal in java using Integer.toHexString() method or custom logic.
|
How to convert Java Decimal to Hex using Interger.toHexString() method?
|
The Integer.toHexString() method converts decimal to hexadecimal. The signature of toHexString() method is given below:
public static String toHexString(int decimal)
|
How to convert Java Octal to Decimal?
|
We can convert octal to decimal in java using Integer.parseInt() method or custom logic.
|
How to convert Java Octal to Decimal conversion: Integer.parsenInt()?
|
he Integer.parseInt() method converts a string to an int with the given radix. If you pass 8 as a radix, it converts an octal string into decimal. Let us see the signature of parseInt() method:
|
How to convert Java Decimal to Octal?
|
We can convert decimal to octal in java using Integer.toOctalString() method or custom logic.
|
Java Decimal to Octal conversion: Integer.toOctalString()
|
The Integer.toOctalString() method converts decimal to octal string. The signature of toOctalString() method is given below:
public static String toOctalString(int decimal)
|
What is Collections in Java?
|
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
|
What is Collection in Java?
|
A Collection represents a single unit of objects, i.e., a group.
|
What is a framework in Java?
|
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
|
What is Collection framework?
|
The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
|
What are the Methods of Collection interface?
|
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
Method: public boolean add(E e)
Description: It is used to insert an element in this collection.
Method: public boolean addAll(Collection<? extends E> c)
Description: It is used to insert the specified collection elements in the invoking collection.
Method: public boolean remove(Object element)
Description: It is used to delete an element from the collection.
Method: public boolean removeAll(Collection<?> c)
Description: It is used to delete all the elements of the specified collection from the invoking collection.
Method: default boolean removeIf(Predicate<? super E> filter)
Description: It is used to delete all the elements of the collection that satisfy the specified predicate.
Method: public boolean retainAll(Collection<?> c)
Description: It is used to delete all the elements of invoking collection except the specified collection.
Method: public int size()
Description: It returns the total number of elements in the collection.
Method: public void clear()
Description: It removes the total number of elements from the collection.
Method: public boolean contains(Object element)
Description: It is used to search an element.
Method: public boolean containsAll(Collection<?> c)
Description: It is used to search the specified collection in the collection.
Method: public Iterator iterator()
Description: It returns an iterator.
Method: public Object[] toArray()
Description: It converts collection into array.
Method: public <T> T[] toArray(T[] a)
Description: It converts collection into array. Here, the runtime type of the returned array is that of the specified array.
Method: public boolean isEmpty()
Description: It checks if collection is empty.
Method: default Stream<E> parallelStream()
Description: It returns a possibly parallel Stream with the collection as its source.
Method: default Stream<E> stream()
Description: It returns a sequential Stream with the collection as its source.
Method: default Spliterator<E> spliterator()
Description: It generates a Spliterator over the specified elements in the collection.
Method: public boolean equals(Object element)
Description: It matches two collections.
Method: public int hashCode()
Description: It returns the hash code number of the collection.
|
What is Iterator interface?
|
Iterator interface provides the facility of iterating the elements in a forward direction only.
|
What are the Methods of Iterator interface?
|
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
Method: public boolean hasNext()
Description:It returns true if the iterator has more elements otherwise it returns false.
Method: public Object next()
Description:It returns the element and moves the cursor pointer to the next element.
Method: public void remove()
Description:It removes the last elements returned by the iterator. It is less used.
|
What is iterable Interface?
|
he Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface.
It contains only one abstract method. i.e.,
Iterator<T> iterator()
It returns the iterator over the elements of type T.
|
What is Collection Interface?
|
The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the methods that every collection will have. In other words, we can say that the Collection interface builds the foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection interface.
|
What is Java ArrayList?
|
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
The important points about the Java ArrayList class are:
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because the array works on an index basis.
In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.
We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases. For example:
ArrayList<int> al = ArrayList<int>(); // does not work
ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
|
What is the class declaration for ArrayList class?
|
Let's see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
|
What are the Constructors of the ArrayList?
|
Constructors of ArrayList
Constructor: ArrayList()
Description: It is used to build an empty array list.
Constructor: ArrayList(Collection<? extends E> c)
Description: It is used to build an array list that is initialized with the elements of the collection c.
Constructor: ArrayList(int capacity)
Description: It is used to build an array list that has the specified initial capacity.
|
What are the Methods of ArrayList?
|
Methods of ArrayList
Method: void add(int index, E element)
Description: It is used to insert the specified element at the specified position in a list.
Method: boolean add(E e)
Description: It is used to append the specified element at the end of a list.
Method: boolean addAll(Collection<? extends E> c)
Description: It is used to append 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.
Method: boolean addAll(int index, Collection<? extends E> c)
Description: It is used to append all the elements in the specified collection, starting at the specified position of the list.
Method: void clear()
Description: It is used to remove all of the elements from this list.
Method: void ensureCapacity(int requiredCapacity)
Description: It is used to enhance the capacity of an ArrayList instance.
Method: E get(int index)
Description: It is used to fetch the element from the particular position of the list.
Method: boolean isEmpty()
Description: It returns true if the list is empty, otherwise false.
Method: Iterator() listIterator() int lastIndexOf(Object o)
Description: It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Method: Object[] toArray()
Description: It is used to return an array containing all of the elements in this list in the correct order.
Method: <T> T[] toArray(T[] a)
Description: It is used to return an array containing all of the elements in this list in the correct order.
Method: Object clone()
Description: It is used to return a shallow copy of an ArrayList.
Method: boolean contains(Object o)
Description: It returns true if the list contains the specified element.
Method: int indexOf(Object o)
Description: It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
Method: E remove(int index)
Description: It is used to remove the element present at the specified position in the list.
Method: boolean remove(Object o)
Description: It is used to remove the first occurrence of the specified element.
Method: boolean removeAll(Collection<?> c)
Description: It is used to remove all the elements from the list.
Method: boolean removeIf(Predicate<? super E> filter)
Description: It is used to remove all the elements from the list that satisfies the given predicate.
Method: protected void removeRange(int fromIndex, int toIndex)
Description: It is used to remove all the elements lies within the given range.
Method: void replaceAll(UnaryOperator<E> operator)
Description: It is used to replace all the elements from the list with the specified element.
Method: void retainAll(Collection<?> c)
Description: It is used to retain all the elements in the list that are present in the specified collection.
Method: E set(int index, E element)
Description: It is used to replace the specified element in the list, present at the specified position.
Method: void sort(Comparator<? super E> c)
Description: It is used to sort the elements of the list on the basis of the specified comparator.
Method: Spliterator<E> spliterator()
Description: It is used to create a spliterator over the elements in a list.
Method: List<E> subList(int fromIndex, int toIndex)
Description: It is used to fetch all the elements that lies within the given range.
Method: int size()
Description: It is used to return the number of elements present in the list.
Method: void trimToSize()
Description: It is used to trim the capacity of this ArrayList instance to be the list's current size.
|
What are the differences between Java Non-generic and Generic Collection?
|
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in a collection. Now it is type-safe, so typecasting is not required at runtime.
Let's see the old non-generic example of creating a Java collection.
ArrayList list=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of object in it. If you try to add another type of object, it gives a compile-time error.
|
Can you provide an example of Java ArrayList?
|
FileName: ArrayListExample1.java
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}
Output:
[Mango, Apple, Banana, Grapes]
|
How to Sort ArrayList?
|
The java.util package provides a utility class Collections, which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
|
What are the ways to iterate the elements of the collection in Java?
|
There are various ways to traverse the collection elements:
1.By Iterator interface.
2.By for-each loop.
3.By ListIterator interface.
4.By for loop.
5.By forEach() method.
6.By forEachRemaining() method.
|
Can you provide an example of traversing the ArrayList elements?
|
Let's see an example to traverse the ArrayList elements through other ways
FileName: ArrayList4.java
import java.util.*;
class ArrayList4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
System.out.println("Traversing list through List Iterator:");
//Here, element iterates in reverse order
ListIterator<String> list1=list.listIterator(list.size());
while(list1.hasPrevious())
{
String str=list1.previous();
System.out.println(str);
}
System.out.println("Traversing list through for loop:");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
System.out.println("Traversing list through forEach() method:");
//The forEach() method is a new feature, introduced in Java 8.
list.forEach(a->{ //Here, we are using lambda expression
System.out.println(a);
});
System.out.println("Traversing list through forEachRemaining() method:");
Iterator<String> itr=list.iterator();
itr.forEachRemaining(a-> //Here, we are using lambda expression
{
System.out.println(a);
});
}
}
Output:
Traversing list through List Iterator:
Ajay
Ravi
Vijay
Ravi
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach() method:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay
|
Can you provide an example of User-defined class objects in Java ArrayList?
|
Let's see an example where we are storing Student class object in an array list.
FileName: ArrayList5.java
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
class ArrayList5{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
|
Can you provide an example of Java ArrayList Serialization and Deserialization?
|
Let's see an example to serialize an ArrayList object and then deserialize it.
FileName: ArrayList6.java
import java.io.*;
import java.util.*;
class ArrayList6 {
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
try
{
//Serialization
FileOutputStream fos=new FileOutputStream("file");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(al);
fos.close();
oos.close();
//Deserialization
FileInputStream fis=new FileInputStream("file");
ObjectInputStream ois=new ObjectInputStream(fis);
ArrayList list=(ArrayList)ois.readObject();
System.out.println(list);
}catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
[Ravi, Vijay, Ajay]
|
Can you provide an example of Java ArrayList to add elements?
|
Here, we see different ways to add an element.
FileName: ArrayList7.java
import java.util.*;
class ArrayList7{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
System.out.println("Initial list of elements: "+al);
//Adding elements to the end of the list
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After invoking add(E e) method: "+al);
//Adding an element at the specific position
al.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+al);
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
//Adding second list elements to the first list
al.addAll(al2);
System.out.println("After invoking addAll(Collection<? extends E> c) method: "+al);
ArrayList<String> al3=new ArrayList<String>();
al3.add("John");
al3.add("Rahul");
//Adding second list elements to the first list at specific position
al.addAll(1, al3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+al);
}
}
Output:
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
|
Can you provide an example of Java ArrayList to remove elements?
|
Here, we see different ways to remove an element.
FileName: ArrayList8.java
import java.util.*;
class ArrayList8 {
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Anuj");
al.add("Gaurav");
System.out.println("An initial list of elements: "+al);
//Removing specific element from arraylist
al.remove("Vijay");
System.out.println("After invoking remove(object) method: "+al);
//Removing element on the basis of specific position
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);
//Creating another arraylist
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
//Adding new elements to arraylist
al.addAll(al2);
System.out.println("Updated list : "+al);
//Removing all the new elements from arraylist
al.removeAll(al2);
System.out.println("After invoking removeAll() method: "+al);
//Removing elements on the basis of specified condition
al.removeIf(str -> str.contains("Ajay")); //Here, we are using Lambda expression
System.out.println("After invoking removeIf() method: "+al);
//Removing all the elements available in the list
al.clear();
System.out.println("After invoking clear() method: "+al);
}
}
Output:
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []
|
What are the important points in Java LinkedList class?
|
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
-Java LinkedList class can contain duplicate elements.
-Java LinkedList class maintains insertion order.
-Java LinkedList class is non synchronized.
-In Java LinkedList class, manipulation is fast because no shifting needs to occur.
-Java LinkedList class can be used as a list, stack or queue.
Hierarchy of LinkedList class
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and implements List and Deque interfaces.
Doubly Linked List
In the case of a doubly linked list, we can add or remove elements from both sides.
|
What is the class declaration for LinkedList class?
|
Let's see the declaration for java.util.LinkedList class.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable
|
What are the Constructors of Java LinkedList?
|
Constructor: LinkedList()
Description: It is used to construct an empty list.
Constructor: LinkedList(Collection<? extends E> c)
Description: It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection's iterator.
|
What are the Methods of Java LinkedList?
|
Method: boolean add(E e)
Description: It is used to append the specified element to the end of a list.
Method: void add(int index, E element)
Description: It is used to insert the specified element at the specified position index in a list.
Method: boolean addAll(Collection<? extends E> c)
Description: It is used to append 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.
Method: boolean addAll(Collection<? extends E> c)
Description: It is used to append 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.
Method: boolean addAll(int index, Collection<? extends E> c)
Description: It is used to append all the elements in the specified collection, starting at the specified position of the list.
Method: void addFirst(E e)
Description: It is used to insert the given element at the beginning of a list.
Method: void addLast(E e)
Description: It is used to append the given element to the end of a list.
Method: void clear()
Description: It is used to remove all the elements from a list.
Method: Object clone()
Description: It is used to return a shallow copy of an ArrayList.
Method: boolean contains(Object o)
Description: It is used to return true if a list contains a specified element.
Method: Iterator<E> descendingIterator()
Description: It is used to return an iterator over the elements in a deque in reverse sequential order.
Method: E element()
Description: It is used to retrieve the first element of a list.
Method: E get(int index)
Description: It is used to return the element at the specified position in a list.
Method: E getFirst()
Description: It is used to return the first element in a list.
Method: E getLast()
Description: It is used to return the last element in a list.
Method: int indexOf(Object o)
Description: It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element.
Method: int lastIndexOf(Object o)
Description: It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element.
Method: ListIterator<E> listIterator(int index)
Description: It is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list.
Method: boolean offer(E e)
Description: It adds the specified element as the last element of a list.
Method: boolean offerFirst(E e)
Description: It inserts the specified element at the front of a list.
Method: boolean offerLast(E e)
Description: It inserts the specified element at the end of a list.
Method: E peek()
Description: It retrieves the first element of a list
Method: E peekFirst()
Description: It retrieves the first element of a list or returns null if a list is empty.
Method: E peekLast()
Description: It retrieves the last element of a list or returns null if a list is empty.
Method: E poll()
Description: It retrieves and removes the first element of a list.
Method: E pollFirst()
Description: It retrieves and removes the first element of a list, or returns null if a list is empty.
Method: E pollLast()
Description: It retrieves and removes the last element of a list, or returns null if a list is empty.
Method: E pop()
Description: It pops an element from the stack represented by a list.
Method: void push(E e)
Description: It pushes an element onto the stack represented by a list.
Method: E remove()
Description: It is used to retrieve and removes the first element of a list.
Method: E remove(int index)
Description: It is used to remove the element at the specified position in a list.
Method: boolean remove(Object o)
Description: It is used to remove the first occurrence of the specified element in a list.
Method: E removeFirst()
Description: It removes and returns the first element from a list.
Method: boolean removeFirstOccurrence(Object o)
Description: It is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail).
Method: E removeLast()
Description: It removes and returns the last element from a list.
Method: boolean removeLastOccurrence(Object o)
Description: It removes the last occurrence of the specified element in a list (when traversing the list from head to tail).
Method: E set(int index, E element)
Description: It replaces the element at the specified position in a list with the specified element.
Method: Object[] toArray()
Description: It is used to return an array containing all the elements in a list in proper sequence (from first to the last element).
Method: <T> T[] toArray(T[] a)
Description: It returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array.
Method: int size()
Description: It is used to return the number of elements in a list.
|
Can you provide an example of Java LinkedList?
|
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output: Ravi
Vijay
Ravi
Ajay
|
What are the difference between ArrayList and LinkedList?
|
ArrayList and LinkedList both implement the List interface and maintain insertion order. Both are non-synchronized classes.
However, there are many differences between the ArrayList and LinkedList classes that are given below.
1) ArrayList internally uses a dynamic array to store the elements while LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the other elements are shifted in memory while Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only while LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data while LinkedList is better for manipulating data.
5) The memory location for the elements of an ArrayList is contiguous while The location for the elements of a linked list is not contagious.
6) Generally, when an ArrayList is initialized, a default capacity of 10 is assigned to the ArrayList while There is no case of default capacity in a LinkedList. In LinkedList, an empty list is created when a LinkedList is initialized.
7) To be precise, an ArrayList is a resizable array while LinkedList implements the doubly linked list of the list interface.
|
Can you provide an example of ArrayList and LinkedList in Java?
|
Let's see a simple example where we are using ArrayList and LinkedList both.
FileName: TestArrayLinked.java
import java.util.*;
class TestArrayLinked{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
List<String> al2=new LinkedList<String>();//creating linkedlist
al2.add("James");//adding object in linkedlist
al2.add("Serena");
al2.add("Swati");
al2.add("Junaid");
System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
}
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
|
What is Java List?
|
List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.
List Interface declaration
public interface List<E> extends Collection<E>
|
What are the methods of Java List?
|
Method: void add(int index, E element)
Description: It is used to insert the specified element at the specified position in a list.
Method: boolean add(E e)
Description: It is used to append the specified element at the end of a list.
Method: boolean addAll(Collection<? extends E> c)
Description: It is used to append all of the elements in the specified collection to the end of a list.
Method: boolean addAll(int index, Collection<? extends E> c)
Description: It is used to append all the elements in the specified collection, starting at the specified position of the list.
Method: void clear()
Description: It is used to remove all of the elements from this list.
Method: boolean equals(Object o)
Description: It is used to compare the specified object with the elements of a list.
Method: int hashcode()
Description: It is used to return the hash code value for a list.
Method: E get(int index)
Description: It is used to fetch the element from the particular position of the list.
Method: boolean isEmpty()
Description: It returns true if the list is empty, otherwise false.
Method: int lastIndexOf(Object o)
Description: It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Method: Object[] toArray()
Description: It is used to return an array containing all of the elements in this list in the correct order.
Method: <T> T[] toArray(T[] a)
Description: It is used to return an array containing all of the elements in this list in the correct order.
Method: boolean contains(Object o)
Description: It returns true if the list contains the specified element
Method: boolean containsAll(Collection<?> c)
Description: It returns true if the list contains all the specified element
Method: int indexOf(Object o)
Description: It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
Method: E remove(int index)
Description: It is used to remove the element present at the specified position in the list.
Method: boolean remove(Object o)
Description: It is used to remove the first occurrence of the specified element.
Method: boolean removeAll(Collection<?> c)
Description: It is used to remove all the elements from the list.
Method: void replaceAll(UnaryOperator<E> operator)
Description: It is used to replace all the elements from the list with the specified element.
Method: void retainAll(Collection<?> c)
Description: It is used to retain all the elements in the list that are present in the specified collection.
Method: E set(int index, E element)
Description: It is used to replace the specified element in the list, present at the specified position.
Method: void sort(Comparator<? super E> c)
Description: It is used to sort the elements of the list on the basis of specified comparator.
Method: Spliterator<E> spliterator()
Description: It is used to create spliterator over the elements in a list.
Method: List<E> subList(int fromIndex, int toIndex)
Description: It is used to fetch all the elements lies within the given range.
Method: int size()
Description: It is used to return the number of elements present in the list.
|
What is Java List and ArrayList?
|
List is an interface whereas ArrayList is the implementation class of List.
|
How to create a List in Java?
|
The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to create the List:
//Creating a List of type String using ArrayList
List<String> list=new ArrayList<String>();
//Creating a List of type Integer using ArrayList
List<Integer> list=new ArrayList<Integer>();
//Creating a List of type Book using ArrayList
List<Book> list=new ArrayList<Book>();
//Creating a List of type String using LinkedList
List<String> list=new LinkedList<String>();
In short, you can create the List of any type. The ArrayList<T> and LinkedList<T> classes are used to specify the type. Here, T denotes the type.
|
Can you provide an example of Java List?
|
Let's see a simple example of List where we are using the ArrayList class as the implementation.
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Output:
Mango
Apple
Banana
Grapes
|
How to convert Array to List?
|
We can convert the Array to List by traversing the array and adding the element in list one by one using list.add() method. Let's see a simple example to convert array elements into List.
import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
//Converting Array to List
List<String> list=new ArrayList<String>();
for(String lang:array){
list.add(lang);
}
System.out.println("Printing List: "+list);
}
}
Output:
Printing Array: [Java, Python, PHP, C++]
Printing List: [Java, Python, PHP, C++]
|
How to convert List to Array?
|
We can convert the List to Array by calling the list.toArray() method. Let's see a simple example to convert list elements into array.
import java.util.*;
public class ListToArrayExample{
public static void main(String args[]){
List<String> fruitList = new ArrayList<>();
fruitList.add("Mango");
fruitList.add("Banana");
fruitList.add("Apple");
fruitList.add("Strawberry");
//Converting ArrayList to Array
String[] array = fruitList.toArray(new String[fruitList.size()]);
System.out.println("Printing Array: "+Arrays.toString(array));
System.out.println("Printing List: "+fruitList);
}
}
Output:
Printing Array: [Mango, Banana, Apple, Strawberry]
Printing List: [Mango, Banana, Apple, Strawberry]
|
What is Get and Set Element in List?
|
The get() method returns the element at the given index, whereas the set() method changes or replaces the element.
import java.util.*;
public class ListExample2{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//accessing the element
System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because index starts from 0
//changing the element
list.set(1,"Dates");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Output:
Returning element: Apple
Mango
Dates
Banana
Grapes
|
How to Sort List?
|
There are various ways to sort the List, here we are going to use Collections.sort() method to sort the list element. The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort any List.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
|
What is Java ListIterator Interface?
|
ListIterator Interface is used to traverse the element in a backward and forward direction.
|
What is the class declaration for Listlterator Interface?
|
public interface ListIterator<E> extends Iterator<E>
|
What are the Methods of Java ListIterator Interface?
|
Method: void add(E e)
Description: This method inserts the specified element into the list.
Method: boolean hasNext()
Description: This method returns true if the list iterator has more elements while traversing the list in the forward direction.
Method: E next()
Description: This method returns the next element in the list and advances the cursor position.
Method: int nextIndex()
Description: This method returns the index of the element that would be returned by a subsequent call to next()
Method: boolean hasPrevious()
Description: This method returns true if this list iterator has more elements while traversing the list in the reverse direction.
Method: E previous()
Description: This method returns the previous element in the list and moves the cursor position backward.
Method: E previousIndex()
Description: This method returns the index of the element that would be returned by a subsequent call to previous().
Method: void remove()
Description: This method removes the last element from the list that was returned by next() or previous() methods
Method: void set(E e)
Description: This method replaces the last element returned by next() or previous() methods with the specified element.
|
Can you provide an example of ListIterator Interface?
|
import java.util.*;
public class ListIteratorExample1{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
System.out.println("Traversing elements in forward direction");
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
}
}
Output:
Traversing elements in forward direction
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit
|
Can you provide an example of List: Book?
|
Let's see an example of List where we are adding the Books.
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ListExample5 {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications and Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
|
What are the important points about Java HashSet?
|
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
-HashSet stores the elements by using a mechanism called hashing.
-HashSet contains unique elements only.
-HashSet allows null value.
-HashSet class is non synchronized.
-HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
-HashSet is the best approach for search operations.
-The initial default capacity of HashSet is 16, and the load factor is 0.75.
|
What is the Difference between List and Set?
|
A list can contain duplicate elements whereas Set contains unique elements only.
|
What are the Constructors of the Java HashSet class?
|
Sn:1
Constructor: HashSet()
Description: It is used to construct a default HashSet.
Sn:2
Constructor: HashSet(int capacity)
Description: It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
Sn:3
Constructor: HashSet(int capacity, float loadFactor)
Description: It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
Sn:4
Constructor: HashSet(Collection<? extends E> c)
Description: It is used to initialize the hash set by using the elements of the collection c.
|
What are the Methods of Java HashSet class?
|
Various methods of Java HashSet class are as follows:
Sn:1
Method and Type: boolean
Method: add(E e)
Description: It is used to add the specified element to this set if it is not already present.
Sn:2
Method and Type: void
Method: clear()
Description: It is used to remove all of the elements from the set.
Sn:3
Method and Type: object
Method: clone()
Description: It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
Sn:4
Method and Type: boolean
Method: contains(Object o)
Description: It is used to return true if this set contains the specified element.
Sn:5
Method and Type: boolean
Method: isEmpty()
Description: It is used to return true if this set contains no elements.
Sn:6
Method and Type: Iterator<E>
Method: iterator()
Description: It is used to return an iterator over the elements in this set.
Sn:7
Method and Type: boolean
Method: remove(Object o)
Description: It is used to remove the specified element from this set if it is present.
Sn:8
Method and Type: int
Method: size()
Description: It is used to return the number of elements in the set.
Sn:9
Method and Type: Spliterator<E>
Method: spliterator()
Description: It is used to create a late-binding and fail-fast Spliterator over the elements in the set.
|
Can you provide an example of Java HashSet?
|
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Five
One
Four
Two
Three
|
What is the important points about the Java LinkedHashSet Class?
|
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface.
It inherits the HashSet class and implements the Set interface.
The important points about the Java LinkedHashSet class are:
-Java LinkedHashSet class contains unique elements only like HashSet.
-Java LinkedHashSet class provides all optional set operations and permits null elements.
-Java LinkedHashSet class is non-synchronized.
-Java LinkedHashSet class maintains insertion order.
|
What is the class declaration for LinkedHashSet class?
|
Let's see the declaration for java.util.LinkedHashSet class.
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable
|
What are the Constructors of the Java LinkedHashSet class?
|
Constructor: HashSet()
Description: It is used to construct a default HashSet.
Constructor: HashSet(Collection c)
Description: It is used to initialize the hash set by using the elements of the collection c.
Constructor: LinkedHashSet(int capacity)
Description: It is used to initialize the capacity of the linked hash set to the given integer value capacity.
Constructor: LinkedHashSet(int capacity, float fillRatio)
Description: It is used to initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument.
|
Can you provide an example of Java LinkedHashSet?
|
Let's see a simple example of the Java LinkedHashSet class. Here you can notice that the elements iterate in insertion order.
FileName: LinkedHashSet1.java
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
LinkedHashSet<String> set=new LinkedHashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output:
One
Two
Three
Four
Five
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.