简体   繁体   中英

How to put INT into name of variable

So i have a lot of variables called really similar.

im1=...;
im2=...;//And so on

I need to be able to use .setText(); with it. I also have a int that shows what variable do i need. How can i make this stuff?

int number=2;
im<number>.setText();// I want to make this like im2.setText();

You could use reflection to do that. But reflection is slow and error-prone, and should be used only as a last resort.

Better to use other data structures provided by Java.

Array

An array gives you an sequence of objects. Access each element by way of an annoyingly zero-based index number.

String[] names = new String[ 3 ] ;

names[ 0 ] = "Alice" ;
names[ 1 ] = "Bob" ;
names[ 2 ] = "Carol" ;

If your variable number is one-based ordinal number, just subtract one to access array.

String name = names[ number - 1 ] ;

List

List is similar to array, but much more flexible and helpful.

List< String > names = List.of( "Alice", "Bob", "Carol" ) ;

Retrieval in List also uses annoying zero-based index counting.

String name = names.get( number - 1 ) ;

NavigableSet

If you want to collect objects in sorted order, use an implementation of the NavigableSet interface. The Java platform includes two, TreeSet and ConcurrentSkipListSet .

Third parties may also provide implementations. Perhaps in Google Guava , or Eclipse Collections .

Map

And I suggest you learn about key-value pairs in a Map .

Map< Integer , String > numberedNames = 
    Map.of( 
        1 , "Alice" ,
        2 , "Bob" ,
        3 , "Carol" 
    )
;

Retrieval.

String name = numberedNames.get( number ) ;

The code shown here transparently uses auto-boxing to automatically convert from int primitive values to Integer objects.


See the tutorials online provided free of cost by Oracle. They cover all three, arrays, List , and Map .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM