Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a functionality in Java similar to C#'s anonymous types?

I was wondering if there exists a similar functionality in Java similar to C#'s anonymous types:

var a = new {Count = 5, Message = "A string."};

Or does this concept go against the Java paradigm?

EDIT:

I suppose using Hashable() in Java is somewhat similar.

like image 374
Ivan Avatar asked Jul 22 '11 18:07

Ivan


People also ask

Is there any similarity between C and Java?

Similarities Between Java and C++Both the languages support object-oriented programming. They have the very same type of syntax. The comments syntax is identical between Java and C++. The conditional statements (such as switch, if-else, etc.)

Does Java have C like syntax?

If you are a C or C++ programmer, you should have found much of the syntax of Java--particularly at the level of operators and statements--to be familiar. Because Java and C are so similar in some ways, it is important for C and C++ programmers to understand where the similarities end.

Is Java related to C?

The language later evolved to become Java. A high-level programming language which targets low-level hardware, most commonly used in the programming of FPGAs. It is a rich subset of C. A class-based, single inheritance, object-oriented language with C-style syntax.

How does Java compare to C?

C is a procedural, low level, and compiled language. Java is an object-oriented, high level, and interpreted language. Java uses objects, while C uses functions. Java is easier to learn and use because it's high level, while C can do more and perform faster because it's closer to machine code.


2 Answers

No. There is no equivalent. There is no typeless variable declaration (var) in Java that the Java compiler could fill in with the auto-generated type name to allow a.Count and a.Message to be accessed.

like image 141
Mike Samuel Avatar answered Sep 30 '22 15:09

Mike Samuel


Maybe you mean sth like this:

Object o = new Object(){
    int count = 5;
    String message = "A string.";
};

@Commenters: of course this is a theoretical, very inconvenient example.

Probably OP may use Map:

Map<String,Object> a = new HashMap<String,Object>();
a.put("Count", 5);
a.put("Message", "A string.");

int count = (Integer)a.get("Count"); //better use Integer instead of int to avoid NPE
String message = (String)a.get("Message");
like image 40
zacheusz Avatar answered Sep 30 '22 15:09

zacheusz