Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to get element in list without declaring it?

Tags:

java

arrays

I'm trying to do something very simple:

class Test{
    public static void main(String[] args){
        System.out.println({"Beäbuä","Shun", "Kalle", "Pelle","Jorpi","Lelle","Cilla", "Basse","Sebbe","Nisse","Lasse","Paow<3"}[1])
    }
}

This generates 29 errors, saying various things.

What is the problem here? Why can't I get the 1 element of an array this way?

APPLICATION:

I was writing a class with a second constructor generating random names for the original constructor. The list above is a list of names. My problem was that the random generation of names had to be done in the this(inputarg1, inputarg2) line, since this line has to come first in the second constructor.

like image 317
Sahand Avatar asked Nov 29 '25 12:11

Sahand


1 Answers

The compiler doesnt know the type of the array so this needs to be defined explicitly

System.out.println
     (new String[] {"Beäbuä","Shun", "Kalle", "Pelle","Jorpi","Lelle","Cilla", "Basse","Sebbe","Nisse","Lasse","Paow<3"}[1]);
like image 88
Reimeus Avatar answered Dec 02 '25 02:12

Reimeus



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!