Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create some variable type alias in Java

let say I have this code

Map<String, String> list = new HashMap<String, String>(); list.put("number1", "one"); list.put("number2", "two"); 

how can I make some "alias" the type

Map<String, String> 

to something that easier to be rewritten like

// may be something like this theNewType = HashMap<String, String>;  theNewType list = new theNewType(); list.put("number1", "one"); list.put("number2", "two"); 

basically my question is, how to create "alias" to some "type", so i can make it easier to write and easier when need to change the whole program code.

Thanks, and sorry if this is silly question. I'm kinda new in Java.

like image 366
Lee Avatar asked Apr 09 '11 10:04

Lee


People also ask

How do you create an alias variable in Java?

public static void main(String[] args){ MyClass myObject = new MyClass(); ... int[] temp = myObject. getvariable(); // use of temp ... }

What are aliases in Java?

In Java, Alias is used when reference, which is of more than one, is linked to the same object. The issue with aliasing is when a user writes to a particular object, and the owner for the several other references do not expect that object to change.

What is a type alias?

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.


2 Answers

There are no aliases in Java. You can extend the HashMap class with your class like this:

public class TheNewType extends HashMap<String, String> {     // default constructor     public TheNewType() {         super();     }     // you need to implement the other constructors if you need } 

But keep in mind that this will be a class it won't be the same as you type HashMap<String, String>

like image 167
KARASZI István Avatar answered Oct 19 '22 03:10

KARASZI István


There is no typedef equivalent in Java, and there is no common idiom for aliasing types. I suppose you could do something like

class StringMap extends HashMap<String, String> {} 

but this is not common and would not be obvious to a program maintainer.

like image 38
Rom1 Avatar answered Oct 19 '22 05:10

Rom1