1

I have some Map 0f Map 0f List

I created such interface for shorthand it

public interface ShortName extends Map<String, Map<String, List<String>>>

But when I try to instantiate real object it give me ClassCastExcpetion

ShortName testObj = (ShortName) new HashMap<String, Map<String, List<String>>>();

Is there any way to make short type for Map

1
  • 2
    No. No type aliases in Java. Commented Sep 27, 2019 at 10:12

2 Answers 2

0

Java doesn't have a concept of type aliasing (see This question), however you can make a new class, of a different type, which extends your Map;

class NewType extends HashMap<String, Map<String, List<String>>>

But this isn't a "shorthand" for that type, it's a new type altogether - so casting won't work etc.

Sign up to request clarification or add additional context in comments.

Comments

0

This is a way to get a shorthand to work partly. You need to implement ShortName to make ShortName cast work.

You can do public static class NewType extends HashMap<String, Map<String, List<String>>> implements ShortName {}. And then you can use the cast to ShortName as in ShortName testObj = (ShortName) new NewType();

import java.util.Map;
import java.util.HashMap;
import java.util.List;

public class MyClass {
    public static void main(String args[]) {

        ShortName testObj = (ShortName) new NewType();
        System.out.println("ok");
    }

    public interface ShortName extends Map<String, Map<String, List<String>>> {

    }

    public static class NewType extends HashMap<String, Map<String, List<String>>> implements ShortName {}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.