Question

In: Computer Science

I am implementing a generic List class and not getting the expected output. My current output...

I am implementing a generic List class and not getting the expected output.

My current output is: [0, 1, null]

Expected Output in a separate test class:

List list = new SparseList<>(); 
list.add("0");
list.add("1");
list.add(4, "4");

will result in the following list of size 5: [0, 1, null, null, 4].

list.add(3, "Three");

will result in the following list of size 6: [0, 1, null, Three, null, 4].

list.set(3, "Three");

is going to produce a list of size 5 (unchanged): [0, 1, null, Three, 4].

When removing an element from the list above, via list.remove(1); the result should be the following list of size 4: [0, null, Three, 4]

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class SparseList<E> implements List<E>{
    private int endIndex = 0;
    
    private HashMap<Integer,E> list;
    
    public SparseList() {
        list = new HashMap<>();
    }
    
    public SparseList(E[] arr) {
        list = new HashMap<>();
        for(int i = 0; i <arr.length; i++) {
            list.put(i, arr[i]);
        }
        endIndex = arr.length - 1;
    }
    
    @Override
    public boolean add(E e) {
        list.put(endIndex, e);
        endIndex++;
        return true;
    }
    
    @Override
    public void add(int index, E element) {
        list.put(index, element);
    }
    
    @Override
    public E remove(int index) {
        return list.remove(index);
    }
    
    @Override
    public E get(int index) {
        return list.get(index);
    }
    
    @Override
    public E set(int index, E element) {
        E previous = list.get(index);
        list.put(index, element);
        return previous;
    }
    
    @Override
    public int size() {
        return endIndex + 1;
    }

    @Override
    public void clear() {
        list.clear();
        
    }
    
    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public String toString() {
        String s = "";
        for(int i = 0; i < list.size(); i++) {
            if(list.get(i) == null) {
                s += "null, ";
            }else {
            s += list.get(i).toString() + ", ";
        }
        }
        return "[" + s + "]";
    }

    @Override
    public boolean contains(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Iterator<E> iterator() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object[] toArray() {
        throw new UnsupportedOperationException();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        throw new UnsupportedOperationException();
    }


    @Override
    public boolean containsAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }
    
    @Override
    public int indexOf(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int lastIndexOf(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public ListIterator<E> listIterator() {
        throw new UnsupportedOperationException();
    }

    @Override
    public ListIterator<E> listIterator(int index) {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<E> subList(int fromIndex, int toIndex) {
        throw new UnsupportedOperationException();
    }

}

Solutions

Expert Solution

I assume there is a typo in the problem statement where it says this: [0, 1, null, Three, null, 4].

list.set(3, "Three"); is going to produce a list of size 5 (unchanged): [0, 1, null, Three, 4].

There is no logical way that the set will remove the null just before 4. With that in mind, here is the fixed code:

The add, remove and toString functions have been fixed and some comments added.

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class SparseList<E> implements List<E>{
private int endIndex = 0;
  
private HashMap<Integer,E> list;
  
public SparseList() {
list = new HashMap<>();
}
  
public SparseList(E[] arr) {
list = new HashMap<>();
for(int i = 0; i <arr.length; i++) {
list.put(i, arr[i]);
}
endIndex = arr.length - 1;
}
  
@Override
public boolean add(E e) {
list.put(endIndex, e);
endIndex++;
return true;
}
  
@Override
public void add(int index, E element) {
if (endIndex <= index) { // there is no element yet at index
list.put(index, element);
endIndex = index + 1;
}
else { // there is already an element, need to push to higher indexes
for (int i = endIndex - 1; i >= index; i--)
if (list.get(i) != null) {
list.put(i+1, list.get(i));
list.remove(i);
}
list.put(index, element);
endIndex++;
}
}
  
@Override
public E remove(int index) {
E previous = list.remove (index);
for (int i = index; i < endIndex; i++) { // pull in any remaining items
if (list.get (i+1) != null) {
list.put (i, list.get (i + 1) );
list.remove (i + 1);
}
}
endIndex--;
return previous;
}
  
@Override
public E get(int index) {
return list.get(index);
}
  
@Override
public E set(int index, E element) {
E previous = list.get(index);
list.put(index, element);
return previous;
}
  
@Override
public int size() {
return endIndex + 1;
}

@Override
public void clear() {
list.clear();
  
}
  
@Override
public boolean isEmpty() {
return list.isEmpty();
}

@Override
public String toString() {
String s = "";
for(int i = 0; i < endIndex; i++) { // not list.size ()
if(list.get(i) == null) {
s += "null, ";
}else {
s += list.get(i).toString() + ", ";
}
}
// Remove the last unnecessary comma
if (s.length() > 0)
s = s.substring (0, s.length() - 2);
return "[" + s + "]";
}

@Override
public boolean contains(Object o) {
throw new UnsupportedOperationException();
}

@Override
public Iterator<E> iterator() {
throw new UnsupportedOperationException();
}

@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
}

@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}


@Override
public boolean containsAll(Collection<?> c) {
throw new UnsupportedOperationException();
}

@Override
public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}

@Override
public boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException();
}

@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}

@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}

@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
  
@Override
public int indexOf(Object o) {
throw new UnsupportedOperationException();
}

@Override
public int lastIndexOf(Object o) {
throw new UnsupportedOperationException();
}

@Override
public ListIterator<E> listIterator() {
throw new UnsupportedOperationException();
}

@Override
public ListIterator<E> listIterator(int index) {
throw new UnsupportedOperationException();
}

@Override
public List<E> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}

}

// Below is the main program used to test:

import java.util.List;
import java.util.ListIterator;

public class Main
{
   public static void main(String[] args) {
String s;
       List list = new SparseList<>();
list.add("0");
list.add("1");
list.add(4, "4");
       s = list.toString (); System.out.println (s);
list.add(3, "Three");
       s = list.toString (); System.out.println (s);
list.set(4, "Four");
       s = list.toString (); System.out.println (s);
list.remove(1);
       s = list.toString (); System.out.println (s);
   }
}
// Below is the output:

[0, 1, null, null, 4]                                                                                                         

[0, 1, null, Three, null, 4]                                                                                                  

[0, 1, null, Three, Four, 4]                                                                                                  

[0, null, Three, Four, 4]


Related Solutions

I am implementing a generic List class and not getting the expected output. My current output...
I am implementing a generic List class and not getting the expected output. My current output is: [0, 1, null] Expected Output in a separate test class: List list = new SparseList<>(); list.add("0"); list.add("1"); list.add(4, "4"); will result in the following list of size 5: [0, 1, null, null, 4]. list.add(3, "Three"); will result in the following list of size 6: [0, 1, null, Three, null, 4]. list.set(3, "Three"); is going to produce a list of size 5 (unchanged): [0,...
I'm getting an error with my code on my EvenDemo class. I am supposed to have...
I'm getting an error with my code on my EvenDemo class. I am supposed to have two classes, Event and Event Demo. Below is my code.  What is a better way for me to write this? //******************************************************** // Event Class code //******************************************************** package java1; import java.util.Scanner; public class Event {    public final static double lowerPricePerGuest = 32.00;    public final static double higherPricePerGuest = 35.00;    public final static int cutOffValue = 50;    public boolean largeEvent;    private String...
I am having a hard time getting my an output after putting in the second set...
I am having a hard time getting my an output after putting in the second set of functions and I was hoping to be able to have the results from the functions be rounded to 2 decimal places. <html> <head> <title>Length Conversion</title> <script language='JavaScript' type='text/JavaScript'> <!-- function validate(type) { if(document.my_form.textinput.value=='') { alert('Fill the Input box before submitting'); return false; }else{ if(type=="to_feet"){ var res=3.2808*document.my_form.textinput.value; var unit=" feet"; }else{ var res=0.3048*document.my_form.textinput.value; var unit=" meter"; } document.getElementById("result").innerHTML=res.toFixed(2) + unit; return false; } }...
I am taking a Data Structures and Program Design class. BUT, I am having trouble getting...
I am taking a Data Structures and Program Design class. BUT, I am having trouble getting access to the vectors so that I can compare the guesses with the random numbers. I’ve been working on this for several days and don't feel any closer to a solution and could really use some help as I really don't know how to get this to work. Thank you! The assignment is: Design an ADT for a one-person guessing game that chooses 4...
Hi I am getting error in implement some test case using Java. I am adding my...
Hi I am getting error in implement some test case using Java. I am adding my code and relevant files here, and the failed test. Please let me know where my problem is occuring and fix my code. Thanks! I will upvote. Implement a class to perform windowing of a Hounsfield value Implement the class described by this API. A partial implementation is provided for you in the eclipse project; however, unlike the previous class, very little work has been...
I am working on extensive report for my Advanced Corp. Tax class and I am hoping...
I am working on extensive report for my Advanced Corp. Tax class and I am hoping to get a better understanding of the following: -In order for a corporation to make a valid “S” election, the corporation must be a “small business corporation.” Explain the meaning of “small business corporation” in this context. -Explain what ‘separately stated items’ are in regards to Partnerships and S corporations? Give an example of ‘separately stated items’ for each type of entity. -What requirements...
In my government class, I am required to write a letter to my U.S House of...
In my government class, I am required to write a letter to my U.S House of Representative (I’m located in Dallas, Tx) about either three social issue or three political issues we are facing. Can anyone help me out on how I should start my letter. How should I address my concerns.
I am having trouble with my assignment and getting compile errors on the following code. The...
I am having trouble with my assignment and getting compile errors on the following code. The instructions are in the initial comments. /* Chapter 5, Exercise 2 -Write a class "Plumbers" that handles emergency plumbing calls. -The company handles natural floods and burst pipes. -If the customer selects a flood, the program must prompt the user to determine the amount of damage for pricing. -Flood charging is based on the numbers of damaged rooms. 1 room costs $300.00, 2 rooms...
Getting an error with my for loop.  How do I correct it?  I am supposed to: Continuously prompt...
Getting an error with my for loop.  How do I correct it?  I am supposed to: Continuously prompt for the number of minutes of each Rental until the value falls between 60 and 7,200 inclusive. For one of the Rental objects, create a loop that displays Coupon good for 10percent off next rental as many times as there are full hours in the Rental. ///////////////////////////////RentalDemo package java1; import java.util.Scanner; public class RentalDemo { public static void main(String[] args) {    Rental object1 =...
This is for my finance class and I am a bit stuck. We're asked to use...
This is for my finance class and I am a bit stuck. We're asked to use the Delta hedging formula (i.e. how much stock to hold) for the multiperiod binomial model to confirm that a financial derivative paying the stock price at time t=N (i.e. V_N = S_N) must be priced with V_0 = S_0 today.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT