How would you Implement an interface Set in Java using a LinkedList? Please explain and give an example
LinkedList in Java
Linked List are linear data structures where the elements are
not stored in contiguous locations and every element is a separate
object with a data part and address part. The elements are linked
using pointers and addresses. Each element is known as a node. Due
to the dynamicity and ease of insertions and deletions, they are
preferred over the arrays. It also has few disadvantages like the
nodes cannot be accessed directly instead we need to start from the
head and follow through the link to reach to a node we wish to
access.
To store the elements in a linked list we use a doubly linked list
which provides a linear data structure and also used to inherit an
abstract class and implement list and deque interfaces.
In Java, LinkedList class implements the list interface. The LinkedList class also consists of various constructors and methods like other java collections.
Constructors for Java LinkedList:
Set:
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
The methods declared by Set are summarized in the following table −
| Sr.No. | Method & Description |
|---|---|
| 1 |
add( ) Adds an object to the collection. |
| 2 |
clear( ) Removes all objects from the collection. |
| 3 |
contains( ) Returns true if a specified object is an element within the collection. |
| 4 |
isEmpty( ) Returns true if the collection has no elements. |
| 5 |
iterator( ) Returns an Iterator object for the collection, which may be used to retrieve an object. |
| 6 |
remove( ) Removes a specified object from the collection. |
| 7 |
size( ) Returns the number of elements in the collection. |
Example
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality −
import java.util.*;
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try {
for(int i = 0; i < 5; i++) {
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e) {}
Output
[34, 22, 10, 60, 30] The sorted list is: [10, 22, 30, 34, 60] The First element of the set is: 10 The last element of the set is: 60
Now we will see some of the basic operations on the Set i.e. Union, Intersection and Difference.
Let’s take an example of two integer Sets:
Union
In this, we could simply add one Set with other. Since the Set will
itself not allow any duplicate entries, we need not take care of
the common values.
Expected Output:
Union : [0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection
We just need to retain the common values from both Sets.
Expected Output:
Intersection : [0, 1, 3, 4]
Difference
We just need to remove all the values of one Set from the
other.
Expected Output:
Difference : [2, 8, 9]
// Java code for demonstrating union, intersection and difference
// on Set
import java.util.*;
public class Set_example
{
public static void main(String args[])
{
Set<Integer> a = new HashSet<Integer>();
a.addAll(Arrays.asList(new Integer[] {1, 3, 2, 4, 8, 9, 0}));
Set<Integer> b = new HashSet<Integer>();
b.addAll(Arrays.asList(new Integer[] {1, 3, 7, 5, 4, 0, 7, 5}));
// To find union
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);
// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);
// To find the symmetric difference
Set<Integer> difference = new HashSet<Integer>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
}
}
Output:
Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9] Intersection of the two Set[0, 1, 3, 4] Difference of the two Set[2, 8, 9]
Example of LinkedList in Java
import java.util.*;
public class LinkedListExample {
public static void main(String args[]) {
/* Linked List Declaration */
LinkedList<String> linkedlist = new LinkedList<String>();
/*add(String Element) is used for adding
* the elements to the linked list*/
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
linkedlist.add("Item6");
linkedlist.add("Item2");
/*Display Linked List Content*/
System.out.println("Linked List Content: " +linkedlist);
/*Add First and Last Element*/
linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
System.out.println("LinkedList Content after addition: " +linkedlist);
/*This is how to get and set Values*/
Object firstvar = linkedlist.get(0);
System.out.println("First element: " +firstvar);
linkedlist.set(0, "Changed first item");
Object firstvar2 = linkedlist.get(0);
System.out.println("First element after update by set method: " +firstvar2);
/*Remove first and last element*/
linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
/* Add to a Position and remove from a position*/
linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: " +linkedlist);
}
}
Output:
Linked List Content: [Item1, Item5, Item3, Item6, Item2] LinkedList Content after addition: [First Item, Item1, Item5, Item3, Item6, Item2, Last Item] First element: First Item First element after update by set method: Changed first item LinkedList after deletion of first and last element: [Item1, Item5, Item3, Item6, Item2] Final Content: [Newly added item, Item1, Item3, Item6, Item2]
Methods for Java LinkedList:
How would you Implement an interface Set in Java using a LinkedList? Please explain and give an...
PLEASE HELP IN JAVA: This is an exercise in using the java LinkedList class. Using input file words.txt , create a LinkedList BUT you must NOT add a word that is already in the list and you MUST add them in the order received to the end of the list. For example, if your input was cat, cat, dog, mouse, dog, horse your list would now contain cat, dog, mouse, horse. And the head of the list would be cat,...
develop a java program using linkedlist to implement priority queue ADT with following operations: void insert(double priority); int delete_min(); public boolean isEmpty(); double findMin(); double deleteMin() EmptyPQException()
Please teach me how to use function interface by java ● Write a functional interface StringOperator with the method performOperation that takes two references to String objects as parameters. ● In a driver program, use lambda expressions to create two different objects that implement the StringOperator interface. ○ One of them concatenates the two Strings, returning the new String ○ One of them sets the first String to all uppercase and the second String to all lowercase and then concatenates...
please explain how to code using java
-. Implement the ListNode and LinkedIntList as we did in class (you can add other methods if needed). You can reference the coxle in powerpoint slides of LinkedList and your textbook. 2. Implement a LinkedIntList class with the following public operations. a. add(int value) - Adds the given value to the end of the list b.get(int index) - Retums value in list at given index. C.add( int index, int value) - Inserts the...
-please use java 3. Interface: Implement a program that creates an Interfacecalled Vehiclewith the following abstract methods(getters): getMake(), getModel(), getYear(), and creates a Classcalled Carthatimplements the Vehicleinterface. The Carclass also contains instance data that represents the make, model, and year of the carand the constructor to initialize these values.Create a driver class called CarTest, whose main method instantiates a Carobject with the following information: Chevrolet, Impala, 2019, and test the getter methods you implement. 4. Abstract Class: Implement the above...
Polynomial Using LinkedList class of Java Language Description: Implement a polynomial class using a LinkedList defined in Java (1) Define a polynomial that has the following methods for Polynomial a. public Polynomial() POSTCONDITION: Creates a polynomial represents 0 b. public Polynomial(double a0) POSTCONDITION: Creates a polynomial has a single x^0 term with coefficient a0 c. public Polynomial(Polynomial p) POSTCONDITION: Creates a polynomial is the copy of p d. public void add_to_coef(double amount, int exponent) POSTCONDITION: Adds the given amount to...
Please write a Java interface for an integer stack (should have the methods push, pop, toString). Then implement this interface using one of our linked list nodes. Then please write an interface for an integer queue ( should have methods enqueue, dequeue, and toString). Then implement this interface using one of our linked list objects. Please see chapter 3 in the text for a definition of a stack. Please write a program that asks the user for how many numbers...
With java and android programming. Imagine you have an unresponsive user interface. How would you go about troubleshooting it?
The JCF provides numerous classes that implement the List interface, including LinkedList, ArrayList, and Vector. Write code to show how the JCF class ArrayList and LinkedList are used to maintain a grocery list. Verify List methods such as "add()", get(), "remove()", "isEmpty()" and "size()" by implementing a test program. import java.util.ArrayList; import java.util.Iterator; public class GroceryList { static public void main(String[] args){ ArrayList<String> groceryList = new ArrayList<String>(); Iterator<String> iter; groceryList.add("apples"); groceryList.add("bread"); groceryList.add("juice"); groceryList.add("carrots"); groceryList.add("ice cream"); System.out.println("Number of items...
You are to fully program the List interface using Java generics and Javadoc. Please note - an interface doesn't account for implementation. It is just the function definitions and Javadoc. The following functions need to be present - please post screenshot of the code with these functions implemented boolean add(E e) void add(int index, E element) void clear() boolean contains(Object o) boolean equals(Object o) E get(int index) int indexOf(Object o) boolean isEmpty() int lastIndexOf(Object o) E remove(int index) boolean remove(Object...