简体   繁体   中英

Is there a way in which a string array variable can be used as an index in another 2D array in JAVA?

我在JAVA中声明了一个string array d={monday,tuesday,wednesday} wednesday string array d={monday,tuesday,wednesday} 。我想使用"d"作为另一个2D数组e[d][t]的索引,这样当我执行d++ ,星期一变成了星期二.....这可能吗?如果可以,怎么办?

It seems you are looking for

List<String> indexes = new ArrayList<String>();
Map<String, String> map=  new HashMap<String, String>();
//iterate through each keys
for(String index: indexes){
  String value  = map.get(index);
}

If it was C++, you could've possible overriden the ++ operator to increment an element in an array, but not possible in Java (as per my first view).

Still searching, keep the thread open.

Well, you should better use hashmaps to get the design more clear. A possible solution could be as follows.

List<Integer> indices = new ArrayList<Integer>();
Map<Integer, String> map=  new HashMap<Integer, String>();

Integer i= 0;

while(some condition){

   String str= map.get(i++);
}

well, you could use an enum

public enum FOO
{
monday(0),tuesday(1),...;
private int index;
private FOO(int index){ this.index = index; }
public int getIndex(){ return index; }
}

that way, you'll be able to do

FOO d = FOO.monday;
some_array[d.getIndex()][some_index];

and you can also implement some kind of function getNext(), that get you the next day in your enum.

This enumerated map is the best way represent your string values with meaningful numerical order. I would still use a hash map implementation with this however. It would look something like

HashMap<Weekday, ArrayList> = ...

Then you can still easily loop through all the days of the week to get your values.

Caution though. You aren't specific on what kind of values these days are accessing. Presumably more strings. what are your trying to represent, or accomplish?

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