Question

How would you Implement  an interface Set in Java using a LinkedList? Please explain and give an...

How would you Implement  an interface Set in Java using a LinkedList? Please explain and give an example

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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:

  1. LinkedList(): Used to create an empty linked list.
  2. LinkedList(Collection C): Used to create a ordered list which contains all the elements of a specified collection, as returned by the collection’s iterator.

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:

  • [1, 3, 2, 4, 8, 9, 0]
  • [1, 3, 7, 5, 4, 0, 7, 5]

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:

  1. add​(int index, E element): This method Inserts the specified element at the specified position in this list.
  2. add​(E e): This method Appends the specified element to the end of this list.
  3. addAll​(int index, Collection c): This method Inserts all of the elements in the specified collection into this list, starting at the specified position.
  4. 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.
  5. addFirst​(E e): This method Inserts the specified element at the beginning of this list.
  6. addLast​(E e): This method Appends the specified element to the end of this list.
  7. clear​(): This method removes all of the elements from this list.
  8. clone​(): This method returns a shallow copy of this LinkedList.
  9. contains​(Object o): This method returns true if this list contains the specified element.
  10. descendingIterator​(): This method returns an iterator over the elements in this deque in reverse sequential order.
  11. element​(): This method retrieves, but does not remove, the head (first element) of this list.
  12. get​(int index): This method returns the element at the specified position in this list.
  13. getFirst​(): This method returns the first element in this list.
  14. getLast​(): This method returns the last element in this list.
  15. indexOf​(Object o): This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
  16. lastIndexOf​(Object o): This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
  17. listIterator​(int index): This method returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list.
  18. offer​(E e): This method Adds the specified element as the tail (last element) of this list.
  19. offerFirst​(E e): This method Inserts the specified element at the front of this list.
  20. offerLast​(E e): This method Inserts the specified element at the end of this list.
  21. peek​(): This method retrieves, but does not remove, the head (first element) of this list.
  22. peekFirst​(): This method retrieves, but does not remove, the first element of this list, or returns null if this list is empty.
  23. peekLast​(): This method retrieves, but does not remove, the last element of this list, or returns null if this list is empty.
  24. poll​(): This method retrieves and removes the head (first element) of this list.
  25. pollFirst​(): This method retrieves and removes the first element of this list, or returns null if this list is empty.
  26. pollLast​(): This method retrieves and removes the last element of this list, or returns null if this list is empty.
  27. pop​(): This method Pops an element from the stack represented by this list.
  28. push​(E e): This method Pushes an element onto the stack represented by this list.
  29. remove​(): This method retrieves and removes the head (first element) of this list.
  30. remove​(int index): This method removes the element at the specified position in this list.
  31. remove​(Object o): This method removes the first occurrence of the specified element from this list, if it is present.
  32. removeFirst​(): This method removes and returns the first element from this list.
  33. removeFirstOccurrence​(Object o): This method removes the first occurrence of the specified element in this list (when traversing the list from head to tail).
  34. removeLast​(): This method removes and returns the last element from this list.
  35. removeLastOccurrence​(Object o): This method removes the last occurrence of the specified element in this list (when traversing the list from head to tail).
  36. set​(int index, E element): This method replaces the element at the specified position in this list with the specified element.
  37. size​(): This method returns the number of elements in this list.
  38. spliterator​(): This method Creates a late-binding and fail-fast Spliterator over the elements in this list.
  39. toArray​(): This method returns an array containing all of the elements in this list in proper sequence (from first to last element).
  40. toArray​(T[] a): This method returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
Add a comment
Know the answer?
Add Answer to:
How would you Implement  an interface Set in Java using a LinkedList? Please explain and give an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PLEASE HELP IN JAVA: This is an exercise in using the java LinkedList class. Using input...

    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...

    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...

    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...

    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...

    -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...

    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)....

    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...

    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...

    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 -...

    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...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT