Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same linkedlist code different behavior between groovy and java, why

Tags:

java

groovy

I am using linkedlist as a stack in groovy

as doc says, pop() take elm from the first

Stack Method  Equivalent Deque Method  
push(e)       addFirst(e) 
pop()         removeFirst()

so a linkedlist [1,2,3] should pop() 1 2 3

and it does in Java, but does NOT in groovy. WHY?

test below

A.java

import java.util.*;

public class A{


    public static void main(String[] args){

        String[] x = "1/2/3/".split("/");
        LinkedList <String> stack = new LinkedList<String>(Arrays.asList(x));
        System.out.println(stack.pop());
    }
}

compile and run

$ javac A.java
$ java A
1

runing in groovy

$ ln -s A.java A.groovy
$ groovy A.groovy
3

here is my java and groovy version

$ java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-11M4509)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode)

$ groovy -version
Groovy Version: 2.1.5 JVM: 1.6.0_51 Vendor: Apple Inc. OS: Mac OS X
like image 738
farmer1992 Avatar asked Oct 18 '13 03:10

farmer1992


People also ask

Is Java LinkedList doubly linked?

The Java LinkedList APIThe LinkedList class in the Java Collection API library is a doubly linked list implementation of the List and Deque interfaces that form a generic data structure. The LinkedList object allows null to be one of the elements of the list along with its support of all optional list operations.

Are linked lists built into Java?

Linked List is a part of the Collection framework present in java. util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part.


1 Answers

This appears to be a "feature" of groovy. Default Groovy Methods are described as This class defines new groovy methods which appear on normal JDK classes inside the Groovy environment.

One of the methods that DefaultGroovyMethods provides is pop(), which is described as: Removes the last item from the List. So it appears that Groovy is weaving in a different implementation of pop() which is conflicting with what LinkedList provides you by default.

A bug report filed against GDM a few years ago describes it best, and provides some additional commentary: LinkedList seems to implement List and a pop/push method, thus the classes method should not be shadowed by a DGM method. Only if we had a LinkedList#pop/push method in DGM, it should be different.

like image 138
Todd Avatar answered Oct 12 '22 01:10

Todd