Issue
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
You could use reflection to do that. See tutorials by Oracle Corp. 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
. A set eliminates duplicates.
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 Java™ Tutorials online provided free of cost by Oracle. They cover all three, arrays, List
, and Map
.
Answered By - Basil Bourque
Answer Checked By - Senaida (JavaFixing Volunteer)