How to refer to a class when both simple and fully-qualified names clash

  • A+
Category:Languages

Consider the following pathological example:

class Ideone {   static class ArrayList<T> {     ArrayList() {       System.out.println("!!");     }   }    static class java {     static class util {       static class ArrayList<T> {         ArrayList() {           System.out.println("Here");         }       }     }   }    public static void main(String[] args) {     new ArrayList<>();     new java.util.ArrayList<>();     // Can I refer to the "usual" java.util.ArrayList?   } } 

The two instances created in the constructor are of the nested classes.

But how might I refer to the java.util.ArrayList that we all know and love in the same class? We can't import it, and we can't use the fully-qualified name, as the nested class symbols would be used instead.

What can we do in this case? (Other than the obvious - stop using such wantonly evil names for the nested classes).

 


I'm going to go out on a limb and say that it's not possible to refer to it from within Ideone. The only solution that I see is to create another class Idetwo (which is a nestmate of Ideone (i.e. it resides in the same file)) and return a java.util.ArrayList from there for use in Ideone:

import java.util.ArrayList;  class Ideone {     ... }  class Idetwo {     static ArrayList<Integer> getList() {         ArrayList<Integer> list = new ArrayList<>();         list.add(1);         list.add(2);         list.add(3);         return list;     } } 

And you'd just change your Ideone's main method to something like:

public static void main(String[] args) throws Exception {     new Ideone.ArrayList<>();     new Ideone.java.util.ArrayList<>();     Idetwo.getList().forEach(System.out::println); } 

Output:

!! Here 1 2 3 

Note: With this method, importing java.util.ArrayList will work fine. However, if you were to call List<Integer> list = Idetwo.getList(); inside Ideone's main method, you need to import java.util.*, as individual imports will not work (interestingly).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: