Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to create an array of more than one datatype in java If possible, how?

Tags:

java

arrays

list

I want to create an array like the list ones like the ones in python3 in java but I don't know how to do it Ex: {"John", 1, True, 1.7}

Is it possible to create an array of more than one datatype in java If it is possible, how is it done?

like image 616
Carlos Ochoa Avatar asked Jan 28 '26 07:01

Carlos Ochoa


1 Answers

Is it possible to create an array of more than one datatype in java If it is possible

No, not possible. But you're mistaken - in python, this is also impossible.

The trick is, in Python all objects are just 'object', and you have a list of objects. In java, expressions do have a type. Nevertheless, all objects are, well, objects. So:

Object[] o = {"John", 1, true, 1.7};

works. You really don't want this - arrays are low level constructs. You'd want List<Object> o = List.of("John", 1, true, 1.7}; no doubt.

Also, why do you want to store this in a list? It SOUNDS like you want this:

class Person {
    String name;
    int id;
    boolean enrolled;
    double gpa;
}

and then a List<Person>. That is 'the java way'. Junking that stuff in an Object[] is not the java way. When in rome, act like romans. When coding java, write it like java people would. If you do not, anybody else can't read your code, and libraries do not work for you or feel weird and unwieldy. If you insist on programming 'python style', then just use python.

like image 74
rzwitserloot Avatar answered Jan 29 '26 19:01

rzwitserloot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!