Skip to content

Java simple-linked-list - What am I missing? #105

Closed

Description

@Jonah-Horowitz

I'm trying to get through the Java track and I'm really confused about two things to do with the simple-linked-list exercise.

  1. Is there a reason this exercise doesn't make use of polymorphism?
  2. How can I possibly write even the signature of a method that will make the last two test conditions succeed?

Allow me to explain the second confusion, here are the method signatures, followed by the compiler errors or failed tests in each case:
Polymorphism:

public <T> T[] asArray(Class<T> cls)
> error: generic array creation T[] answer = new T[size()];

Primitive array:

public int[] asArray(Class<?> cls)
> error: method containsExactly in class AbstractIntArrayAssert<S> cannot be applied to given types;
>         assertThat(list.asArray(Object.class)).containsExactly(expected);
>                                               ^
>   required: int[]
>   found: Object[]
>   reason: varargs mismatch; Object[] cannot be converted to int
>   where S is a type-variable:
>     S extends AbstractIntArrayAssert<S> declared in class AbstractIntArrayAssert

Integer array:

public Integer[] asArray(Class<?> cls)
> error: no suitable method found for containsExactly(Object[])
> assertThat(list.asArray(Object.class)).containsExactly(expected);
>                                               ^
>     method ObjectEnumerableAssert.containsExactly(Integer...) is not applicable
>       (varargs mismatch; Object[] cannot be converted to Integer)
>     method AbstractObjectArrayAssert.containsExactly(Integer...) is not applicable
>       (varargs mismatch; Object[] cannot be converted to Integer)
>   where CAP#1 is a fresh type-variable:
>     CAP#1 extends AbstractObjectArrayAssert<CAP#1,Integer> from capture of ?

Object array:

public Object[] asArray(Class<?> cls)
> SimpleLinkedListTest > canReturnListAsArray FAILED
> java.lang.AssertionError at SimpleLinkedListTest.java:63

As far as I can tell the last three errors are solely because of a type mismatch and inability for Java and/or the test suite to cast arrays in the obvious way. The first error, as I understand it, is a limitation of Java's polymorphism (even though I have no clue how I'm supposed to implement java.util.Collection<E>.toArray(T[]) correctly without creating a generic array).
I'm guessing that I'm missing something which is either obvious or an idiosyncrasy of Java. Can someone please help?

Activity

  1. matthewmorgan commented on Mar 29, 2016

    @matthewmorgan
    Contributor

    Hi,

    I will take a look and try to help. With a little luck I will have time to answer tonight.

    Thanks

  2. matthewmorgan commented on Mar 29, 2016

    @matthewmorgan
    Contributor

    I think the issue here is that you should be using generics, not casting. If you post your code I could take a look and offer more specific feedback.

    Otherwise, you should feel free to submit a partially working (or not at all working!) solution to exercism and look around at what others have done.

    I don't think there's a fault with the test suite as it is.

  3. Jonah-Horowitz commented on Mar 29, 2016

    @Jonah-Horowitz
    Author

    I haven't cast anything, the testing framework, when testing equality of contents of an Integer[] and an Object[] seems to be trying to cast the Object[] as an Integer[], then throwing a compile-time exception when it doesn't manage to do that. Notice that errors 2 and 3 above reference castings that take place within the containsExactly method's call.
    Also the test suite does not seem to be set up to support generics, or as I have been calling the use of generics polymorphism, which is why I asked my first question - I would have expected the test suite to require the class to be instantiated as e.g. new SimpleLinkedList<Integer>() rather than new SimpleLinkedList() if generics were intended to be used.

    Checking the solutions already submitted, there are 6 other than mine at this time. One seems to have simply returned an Object[] (which I tried, and it didn't work for me) and every other solution uses Array.newInstance(class, size) which it then casts as an array of generics T[] (or U[] in one case).
    My incomplete solution is located here, if you feel like taking a look.

    I guess my problem here is that I try to avoid using reflection when possible (primarily because of the reduced performance), so I didn't look in Array (or in Arrays, where I might naively have expected it to be) for creating an array of a generic type.

    Thank you for your help thus far.

  4. matthewmorgan commented on Mar 29, 2016

    @matthewmorgan
    Contributor

    I'm happy to help. I'll give it a closer look and see what I can figure out. 😄

  5. matthewmorgan commented on Apr 1, 2016

    @matthewmorgan
    Contributor

    @Jonah-Horowitz I see that you are not using casting. I think I might not be understanding your question exactly, so bear with me:

    The example solution that I wrote for this exercise does use casting and reflection in the last method that returns the array. In this case the cast is safe because we know the types will match by design. You can see the code on my submission-- it's the same as what I built here to run the test suite against.

    I certainly don't consider myself a Java guru, but I'm a bit confused about your question about polymorphism-- are you suggesting that the test suite should have multiple overridden methods for testing different classes of inputs? That's exactly what we avoid by using generics-- we get to pass the class as a parameter. In fact, your example earlier:

    public <T> T[] asArray(Class<T> cls)
    

    is using generics. That's what <T> is doing for you-- passing the class as a param.

    The test suite uses integers, but if you build your solution using generics, you could for example pass the following test:

        @Test
        public void canReturnDifferentTypeOfListListAsArray() {
            SimpleLinkedList list = new SimpleLinkedList();
            list.push("A");
            list.push("B");
            list.push("C");
            list.push("D");
            list.push("E");
            String[] expected = {"E", "D", "C", "B", "A"};
            assertThat(list.asArray(String.class)).containsExactly(expected);
        }
    

    It's not hard to imagine building a "real" Simple Linked List implementation and wanting it to be flexible enough to store any type of object.

    I don't know if that makes sense or if I'm addressing your concerns-- please let me know. If you have an alternative implementation that would accept any class of object for storage, and that implementation doesn't use generics, I would love to have a look at it for my own edification.

    Anyway, if I can't help you maybe I can lean on @jtigger or @sit to help.

    Cheers!

  6. Jonah-Horowitz commented on Apr 1, 2016

    @Jonah-Horowitz
    Author

    I'm quite aware of the usefulness of generics, what I'm asking in question 1 is why isn't this exercise encouraging its use more? In other words, why isn't the class SimpleLinkedList parameterized rather than only the method toArray? Essentially, why isn't the simple-linked-list exercise more like the linked-list exercise with respect to generics?
    If you like, I can alter my simple-linked-list solution to use generics in the way I intend and post it here later today, but it would likely not actually compile as a solution to the provided test suite.

    Edit: here's my altered answer (I haven't compiled it so there may be some errors).

    import java.util.NoSuchElementException;
    
    public class SimpleLinkedList<E> {
        private Element<E> head = null;
        private Element<E> tail = null;
    
        public SimpleLinkedList() {
        }
    
        public SimpleLinkedList(E[] begin) {
            for (E i : begin)
                push(i);
        }
    
        public int size() {
            int count = 0;
            for (Element<E> point = head; point != null; point = point.getNext())
                count++;
            return count;
        }
    
        public E pop() {
            if (tail==null)
                throw new NoSuchElementException("Cannot pop from empty list.");
            E answer = tail.getContents();
            if (tail.getPrevious()==null) {
                head = null;
                tail = null;
                return answer;
            }
            tail = tail.getPrevious();
            tail.setNext(null);
            return answer;
        }
    
        public void push(E elem) {
            if (head==null) {
                Element<E> newElem = new Element(elem);
                head = newElem;
                tail = newElem;
            } else {
                Element<E> newElem = new Element(elem, null, tail);
                tail.setNext(newElem);
                tail = newElem;
            }
        }
    
        public void reverse() {
            if (head!=null)
                head.reverse();
            Element<E> temp = head;
            head = tail;
            tail = temp;
        }
    
        public E[] asArray() {
            E[] answer = new E[size()];
            int count = 0;
            for (Element<E> point = tail; point!=null; point=point.getPrevious())
                answer[count++]=point.getContents();
            return answer;
        }
    
        private static class Element<E> {
            private E contents;
            private Element next;
            private Element prev;
    
            public Element(E value) {
                this(value, null, null);
            }
    
            public Element(E value, Element<E> next) {
                this(value, next, null);
            }
    
            public Element(E value, Element<E> next, Element<E> prev) {
                contents = value;
                this.next=next;
                this.prev=prev;
            }
    
            public E getContents() {
                return contents;
            }
    
            public Element<E> getNext() {
                return next;
            }
    
            public Element<E> setNext(Element<E> target) {
                Element<E> old = next;
                next = target;
                return old;
            }
    
            public Element<E> getPrevious() {
                return prev;
            }
    
            public Element<E> setPrevious(Element<E> target) {
                Element<E> old = prev;
                prev = target;
                return old;
            }
    
            /**
             * Reverses the list of elements following this one. If you call it on the head of a list, that head will now be the tail.
             */
            public void reverse() {
                if (next!=null)
                    next.reverse();
                Element<E> temp = next;
                next=prev;
                prev=temp;
            }
        }
    }
  7. matthewmorgan commented on Apr 1, 2016

    @matthewmorgan
    Contributor

    That would be great -- it sounds like we might have the beginnings of a PR
    :)

    On Fri, Apr 1, 2016 at 8:04 AM, Jonah-Horowitz notifications@github.com
    wrote:

    I'm quite aware of the usefulness of generics, what I'm asking in question
    1 is why isn't this exercise encouraging its use more? In other words, why
    isn't the class SimpleLinkedList parameterized rather than only the
    method toArray? Essentially, why isn't the simple-linked-list exercise
    more like the linked-list exercise with respect to generics?
    If you like, I can alter my simple-linked-list solution to use generics in
    the way I intend and post it here later today, but it would likely not
    actually compile as a solution to the provided test suite.

    —
    You are receiving this because you commented.
    Reply to this email directly or view it on GitHub
    #105 (comment)

    Matt Morgan
    Director of Technology
    Dulcet Software LLC
    (734) 926-8142

  8. Jonah-Horowitz commented on Apr 3, 2016

    @Jonah-Horowitz
    Author

    Essentially, here's how I would have written the test suite:

    import java.util.NoSuchElementException;
    import static org.assertj.core.api.Assertions.assertThat;
    import org.junit.Test;
    
    public class SimpleLinkedListTest {
    
        @Test
        public void aNewListIsEmpty() {
            SimpleLinkedList<Object> list = new SimpleLinkedList<>();
            assertThat(list.size()).isEqualTo(0);
        }
    
        @Test
        public void canCreateFromArray() {
            Integer[] values = new Integer[]{1, 2, 3};
            SimpleLinkedList<Integer> list = new SimpleLinkedList<>(values);
            assertThat(list.size()).isEqualTo(3);
        }
    
        @Test(expected = NoSuchElementException.class)
        public void popOnEmptyListWillThrow() {
            SimpleLinkedList<Object> list = new SimpleLinkedList<>();
            list.pop();
        }
    
        @Test
        public void popReturnsLastAddedElement() {
            SimpleLinkedList<Integer> list = new SimpleLinkedList<>();
            list.push(9);
            list.push(8);
            assertThat(list.size()).isEqualTo(2);
            assertThat(list.pop()).isEqualTo(8);
            assertThat(list.pop()).isEqualTo(9);
            assertThat(list.size()).isEqualTo(0);
        }
    
        @Test
        public void reverseReversesList() {
            SimpleLinkedList<Integer> list = new SimpleLinkedList<>();
            list.push(9);
            list.push(8);
            list.push(7);
            list.push(6);
            list.push(5);
            list.reverse();
            assertThat(list.pop()).isEqualTo(9);
            assertThat(list.pop()).isEqualTo(8);
            assertThat(list.pop()).isEqualTo(7);
            assertThat(list.pop()).isEqualTo(6);
            assertThat(list.pop()).isEqualTo(5);
        }
    
        @Test
        public void canReturnListAsArray() {
            SimpleLinkedList<Integer> list = new SimpleLinkedList<>();
            list.push(9);
            list.push(8);
            list.push(7);
            list.push(6);
            list.push(5);
            Integer[] expected = {5, 6, 7, 8, 9};
            assertThat(list.asArray()).containsExactly(expected);
        }
    
        @Test
        public void canReturnEmptyListAsEmptyArray() {
            SimpleLinkedList<Object> list = new SimpleLinkedList<>();
            Object[] expected = {};
            assertThat(list.asArray()).containsExactly(expected);
        }
    
    }

    or possible included some examples with Strings.

    I'm not terribly good at creating exercises - could you elaborate?

  9. matthewmorgan commented on Apr 3, 2016

    @matthewmorgan
    Contributor

    Interesting. Thanks for doing this.

    In your example solution, there seems to be issue around the array creation here:

        public E[] asArray() {
            E[] answer = new E[size()];   // ** this does not compile.
            int count = 0;
            for (Element<E> point = tail; point!=null; point=point.getPrevious())
                answer[count++]=point.getContents();
            return answer;
        }
    

    There's a discussion about this on SO here.

    So, one possible solution is the approach I took, using reflection. Another appears to be type casting.

    What do you propose? Is there a reason you would prefer on to the other? Let's discuss and see if we can get some other folks to weigh in too.

  10. Jonah-Horowitz commented on Apr 3, 2016

    @Jonah-Horowitz
    Author

    Hm, based on the link you provided, it's looking to me like my proposal might be impossible in Java. Particularly of interest was Bill Michell's answer (here). On the other hand, it looks like Radiodef's answer (here) and Lii's comment on it might offer something of a compromise using Java 8's Function interfaces, although I suspect that the test suite would then have to employ Java's new lambda function capabilities (which may make it more confusing for people).

    So it looks to me now like there's three approaches that might work, each with its own drawback:
    Yours which uses reflection (resource heavy, but that's probably irrelevant in an exercise):

    public <T> T[] asArray(Class<T> cls) {
        T[] answer = (T[])Array.newInstance(cls, size());
        ...
    }

    One that uses just casting (not type safe):

    public E[] asArray() {
        E[] answer = (E[])(new Object[size()]);
        ...
    }

    And one that uses functional interfaces (relies on the caller to supply an array generator):

    public E[] asArray(IntFunction<E[]> gen) {
        E[] answer = gen.apply(size());
        ...
    }

    Thoughts?

  11. matthewmorgan commented on Apr 3, 2016

    @matthewmorgan
    Contributor

    I agree that using Function might be a bit too much for this exercise. The linked-list exercise doesn't offer any guidance really-- it uses generics, but doesn't return an array, so this issue doesn't arise.

    I looked at the JDK implementation, and here it is:

        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            if (a.length < size)
                a = (T[])java.lang.reflect.Array.newInstance(
                                    a.getClass().getComponentType(), size);
            int i = 0;
            Object[] result = a;
            for (Node<E> x = first; x != null; x = x.next)
                result[i++] = x.item;
    
            if (a.length > size)
                a[size] = null;
    
            return a;
        }
    

    It looks to me like they favored using the reflection approach there, so it seems like that might be the way to go.

    I did want to point out that your example solution contains something that I missed in mine, which is the parameterization of the SimpleLinkedList class itself, so regardless of what we do about the toArray method I think my parameter oversight should be corrected.

    I still don't know if that gets us any closer to addressing your concerns though. Let me know.

  12. matthewmorgan commented on Apr 7, 2016

    @matthewmorgan
    Contributor

    @Jonah-Horowitz unless you have further changes you want to suggest here, I'll put in a PR to add the parameter T to the class declaration, and close this issue. Thanks!

    Edit: the parameter is in there already, closing the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions