Question

Please use Java only: Background: Java contains several different types of interfaces used to organize collections...

Please use Java only:

Background:

Java contains several different types of interfaces used to organize collections of items. You may already be familiar with the List interface, which is implemented by classes such as the ArrayList. A List represents a collection of elements from which elements can be stored or retreived, in which elements are ordered and can be retrieved by index. A List extends from a Collection, which represents a collection of elements but which may or may not have an order or element index. A Set or Queue is an example of a Collection which is not necessarily a List. Going further, a Collection is an Iterable, a structure which represents a sequence of elements. An Iterable may have persistent elements (such as with a Collection) or it may not (such as a data stream).

In this lab, we will write some utility methods within a class called ListUtils. These three methods will all be static methods, and their purpose will be to perform conversions between objects implementing one type of interface and objects implementing another type. For example, we will write a method for converting from an Iterable object to a Collection, and so on. We will discuss more about how this will work below.

Tip: you will definitely want to import java.util for this lab, since List and all of its relatives use it.

Iterable to Collection task:
public static Collection iterToCollection(Iterable iterable)

_Every Collection is an Iterable but not every Iterable is a Collection. However, if we have an Iterable, it implies a sequence of elements, so we can use that to built a Collection. That is what we will do in this method. To implement the method, we will need to create some kind of Collection object, and add elements from the Iterable's sequence to it one by one.

Hint: we don't want to store the result in a Collection itself, because it is just an interface, but there may be a more familiar choice of structure which implements Collection.

Collection to List task:
public static List collToList(Collection coll)

_As above, every List is a Collection but not every Collection is a List. However, if we have a Collection, it implies a fixed number of elements which can be retrieved in sequence, so we can use that to built a List by numbering the element indices in the order they are retrieved. That is what we will do in this method. To implement the method, we will need to create some kind of List object, and add elements from the Collection.

List to Map task:
public static Map listToMap(List list)

_A Map, sometimes known as an associative array or dictionary, is in some ways similar to a List, except that instead of accessing elements by the indices 0, 1, 2, etc., the elements are accessed by a key, which may or may not be in order, and which may or may not be a number. Every element in a Map is stored as a key-value pair (the value of the element plus the key which is used to access it). Thus, when we call the get() method, instead of passing in an intindex, we pass in the key corresponding to the element we're looking for. An example of a class which implements the Map interface in Java is the HashMap class.

A List is not a Map and a Map is not a List. However a Map stores collections of data indexed by some kind of mapping. A Map is essentially a dictionary which allows us to look up elements in a collection of data using some reference key to find each element. The reference key for a Map can be any data type, but if we make that data type an Integer, then we can use the key to represent a List index. Thus, in this method, we will take a List and use it to build a Mapby using the list index of each element as the element's key within the Map. Thus, if our List contains the elements 2, 4, and 6, then this method will produce a Map with the mappings 0 ⇒ 2, 1 ⇒ 4, and 2 ⇒ 6. As above, this would involve creating an appropriate type of Map and adding the elements from the List.

Please make sure that it passes the following: https://repl.it/@micky123/ImpassionedRoughPrediction

Please be sure that the work is your own, not a duplicate of somebody else's. Thank you.

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

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: There is an error in your test code. Inside the test method test_c2l_2(), you created a HashSet and added all values of array test2 into it, converted the set to a list using collToList() object. Everything is fine upto this point. But then you iterate through each element in the resultant list and compared to the corresponding elements in the test2 ARRAY! You cannot compare them because HashSet DOES NOT preserve the order of elements being added. The order of elements are already lost when you added them to the set, the list returned by collToList() will have the elements in order that they were in the set. So there is no logic in comparing each elements at each index on the array and list. If the array is in sorted order, you can preserve the order by using TreeSet instead of HashSet, but with HashSet, the order is not preserved. You can test this by printing hashset once it is created, also print the list once it is created. As a result of this error, one test will always fail in the given file and please be noted that this is not my mistake.

// ListUtils.java

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class ListUtils {

      // method to convert an Iterable to collection

      public static Collection iterToCollection(Iterable iterable) {

            // creating an ArrayList

            Collection c = new ArrayList();

            // looping through each object in iterable

            for (Object ob : iterable) {

                  // adding to list

                  c.add(ob);

            }

            // returning list

            return c;

      }

      // method to convert a collection to list

      // note: these two methods are pretty similar in working

      public static List collToList(Collection coll) {

            // creating an ArrayList

            List list = new ArrayList();

            // looping through each object in collection

            for (Object ob : coll) {

                  // adding to list

                  list.add(ob);

            }

            return list;

      }

      // method to convert a list to Map

      public static Map listToMap(List list) {

            // creating a HashMap

            Map map = new HashMap();

            int index = 0;

            // looping through each objects

            for (Object ob : list) {

                  // adding to map with key being index and value being object

                  map.put(index, ob);

                  index++;

            }

            //returning map

            return map;

      }

}

/*OUTPUT of JUnit test when done in eclipse*/


Add a comment
Know the answer?
Add Answer to:
Please use Java only: Background: Java contains several different types of interfaces used to organize collections...
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
  • Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement...

    Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement some list functionalities on an ArrrayList of generic type using type parameters in method definition Our goal for this lab is to continue using the divide and conquer approach of splitting a list into its head and tail and keep recursing on the tail (which happens to be smaller). However, instead of trying the approach on a string (a list of characters) we would...

  • This lab serves as an intro to Java Interfaces and an Object-Oriented design strategy towards implementing...

    This lab serves as an intro to Java Interfaces and an Object-Oriented design strategy towards implementing data structures. We will be using Entry.java objects which are key,value pairs, with key being an integer and value being a generic parameter. We will be sorting these Entries according to their key value. The file Entry.java is given to you and does not require any modification. As you should know by now, bucket sort works by placing items into buckets and each bucket...

  • java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait)...

    java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait) where Comparator is an interface in java.util. Database: a class that limits the types it can store to DatabaseTypes. The database will store the data in nodes, just like a linked list. The database will also let the user create an index for the database. An index is a sorted array (or in our case, a sorted ArrayList) of the data so that searches...

  • ***JAVA: Please make "Thing" movies. Objective In this assignment, you are asked to implement a bag...

    ***JAVA: Please make "Thing" movies. Objective In this assignment, you are asked to implement a bag collection using a linked list and, in order to focus on the linked list implementation details, we will implement the collection to store only one type of object of your choice (i.e., not generic). You can use the object you created for program #2 IMPORTANT: You may not use the LinkedList class from the java library. Instead, you must implement your own linked list...

  • JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public...

    JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public E previous() { // Returns the previous Element return null; } Explanation: We have this class with these two implemented inferfaces: The interfaces are: package edu.ics211.h04; /** * Interface for a List211. * * @author Cam Moore * @param the generic type of the Lists. */ public interface IList211 { /** * Gets the item at the given index. * @param index the index....

  • Please help with this Java Program. Thank you! we will be implementing an Ordered List ADT....

    Please help with this Java Program. Thank you! we will be implementing an Ordered List ADT. Our goal is to implement the interface that is provided for this ADT. Notice that there are two interfaces: OrderedListADT builds on ListADT. In this homework, you'll only be responsible for the OrderedListADT. Figure 1: UML Overview 1 Requirements Create a doubly linked implementation of the OrderedListADT interface. Note that the book includes most of the source code for a singly linked implementation of...

  • use intellij idea    main java the professor. Please make sure to only implement what is...

    use intellij idea    main java the professor. Please make sure to only implement what is asked for. You may not add any instance variables to any class, though you may create local variables inside of a method to accomplish its task. No other methods should be created other than the ones listed here. Step 1 Develop the following interface: Interface Name: Queue Interface<T> Access Modifier: public Methods Name: isEmpty Access modifier: public Parameters: none Return type: boolean Name: dequeue...

  • Java program. Code the following interfaces, implement them, and use the interface as a parameter, respectively:...

    Java program. Code the following interfaces, implement them, and use the interface as a parameter, respectively: a. An interface called Printable with a void print() method. b. An interface called EmployeeType with FACULTY and CLASSIFIED integer data. The value of FACULTY is 1 and CLASSIFIED is 2. a. A class called Employee to implement the two interfaces. Its constructor will initialize three instance data as name, employeeType, and salary. Implementation of method print() will display name, employeeType, and salary; salary...

  • *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods...

    *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods that has the following generic methods: (1) Write the following method that returns a new ArrayList. The new list contains the nonduplicate (i.e., distinct) elements from the original list. public static ArrayList removeDuplicates(ArrayList list) (2) Write the following method that shuffles an ArrayList. It should do this specifically by swapping two indexes determined by the use of the random class (use Random rand =...

  • use intellij idea main java wp the professor. Please make sure to only implement what is...

    use intellij idea main java wp the professor. Please make sure to only implement what is asked for. You may not add any instance variables to any class, though you may create local variables inside of a method to accomplish its task. No other methods should be created other than the ones listed here. Step 1 Develop the following interface: Interface Name: Queue Interface<T> Access Modifier: public Methods Name: isEmpty Access modifier: public Parameters: none Return type: boolean Name: dequeue...

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
ADVERTISEMENT