So say if I had a series of String Integers with name, i: i1
, i2
, i3
etc but wanted to make up each name with a combination of a String and an Integer like:
String i1 = "abc";
String i2 = "bca";
String i3 = "cba";
for (int i = 1; i <= 3; i++) {
String a = "i" + i;
int aa = Integer.parseInt(a);
ArrayList<String>.add(aa);
}
How could I achieve this? This for loop just adds "i1", "i2" and "i3" to the List, instead of "abc", "bca" and "cba".
Ah, I misunderstood your question at first. Yes, you can do what you want to do trough reflection.
public class Main {
private String i1 = "abc";
private String i2 = "bca";
private String i3 = "cba";
public static void main(String[] args) {
new Main();
}
public Main(){
for (int i = 1; i <= 3; i++) {
String a = "i" + i;
String f = null;
try {
f = (String) this.getClass().getDeclaredField(a).get(this);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(f);
}
}
}
Output:
abc
bca
cba
Keypoints:
getDeclaredField()
- returns a private field in the given class get()
- returns the value from a field in the given object It should be noted though that you should look into using a Map<String, String>
structure first. Other answers already provide the explanation for this.
You need to use some of the Map implementations.
For example:
String[] words = { "abc", "bca", "cba" };
Map<String, String> map = new HashMap<String, String>();
for (int i = 1; i <= 3; i++) {
String a = "i" + i;
map.put(a, words[i - 1]);
}
At the end, the map looks like:
--key-- | --value--
-------------------
"i1" | "abc"
"i2" | "bca"
"i3" | "cba"
Use Integer.toString() , one of the options is able to use alphabetic characters as well as numerical to represent the String
.
You will also need to create a List
to add your String
s to.
List<String> list = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
list.add(whatever);
}
Or if you are trying to store a mapping of String to Integer, then you should look at Map
, probably HashMap
.
Use a String array:
String[] stringArr = new String[3]
ArrayList<String> list = new ArrayList<String>();
stringArr[0] = "abc";
stringArr[1] = "bca";
stringArr[2] = "cba";
for(int i = 0; i<String.length; i++)
{
list.add(Integer.parseInt(stringArr[i]));
}
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.