'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();
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
