在Java中将字符串存储到数组中

3

我想知道是否可以将字符串变量存储在字符串数组中?我无法很好地解释它,但这是我所做的:

 String st1 = "",st2 = "",st3 = "",st4 = "";
 String[] str = {st1,st2,st3,st4};

很不幸,当我使用for循环时,字符串获取的是st1、st2、st3和st4的值,而不是变量本身。

这正是我想要在我的脑海中实现的。无论何时,例如当我有一个字符串数组:

String[] containsValue = { "hi", "hello", "there" };

String strHi, strHello, strThere;
String[] getContainsValue = { strHi, strHello, strThere };

for (int x = 0; x < getContainsValue.length; x++) {
    getContainsValue[x] = containsValue[x];
}

The value of:
strHi = "hi"
strHello = "hello"
strThere = "there";

基本上,我想将containsValue []的值转移到存储在getContainsValue []中的三个字符串strHi,strHello,strThere中。然后使用for循环将来自containsValue []的值分配给它们。
这可能吗?如果是这样,请您提供一些如何执行此操作的格式。谢谢。

.lenght 当然应该是 .length... - Ben
你所发布的代码应该可以正常工作并完成你所说的传输操作。我不明白你的问题在哪里? - NiranjanBhat
1
@ NiranjanBhat 不会的,它只获取了st1的值,即"",而不是变量本身。 - thenewbie
10个回答

10
你可以使用 Map<K,V>
Map<String,String> map=new HashMap<String,String>();
map.put("strHi","hi");
map.put("strHello","hello");
map.put("strThere","there");

System.out.println(map.get("strHello"));

啊,我能否使用循环动态地将值分配给 MAP? - thenewbie
@thenewbie 如果你的意思是在循环中添加键值对,那么是的,你可以这样做;如果你的意思是创建映射实例,那么也是可以的。 - Luiggi Mendoza

3
你可以使用枚举类作为所需的数组:
public enum EnumModifE {
    str1("1"), str2("2"), str3("3");
    String value;
    EnumModifE(final String s) {
        this.value = s;
    }
    public void setValue(final String s) {
        this.value = s;
    }
}
public class EnumModifM {
    public static void main(final String[] args) {
        for (final EnumModifE eme : EnumModifE.values()) {
            System.out.println(eme + "\t" + eme.value);
        }
        EnumModifE.str1.setValue("Hello");
        EnumModifE.str2.setValue("all");
        EnumModifE.str3.setValue("[wo]men");

        for (final EnumModifE eme : EnumModifE.values()) {
            System.out.println(eme + "\t" + eme.value);
        }
    }
}

输出

str1    1
str2    2
str3    3
str1    Hello
str2    all
str3    [wo]men

请参考《Effective Java》中关于枚举类型的用法。


2
你所寻找的概念是“左值”。简单来说,当你使用一个变量时,你是在使用变量中包含的值,还是在谈论变量本身,以便你可以将其他东西存储到其中?你想要调用 getContainsValue 的数组具有 strHistrHellostrThere 的左值。不幸的是,在Java中没有办法做到这一点。使用 strHistrHellostrThere 来初始化 getContainsValue 使用的是这些变量的,而不是它们的左值
让我们退后一步,更多地讨论左值与值(有时是右值)。考虑以下代码片段:
int i = 17;
i = i + 1;

那第二行显然不是一个方程式,那将是无意义的。相反,它是一个“分配”。在赋值的左右两侧,“i”的含义是不同的。在右侧,“i”表示使用该变量的值,在本例中为17。在左侧,“i”表示变量本身,作为存储值的目标。即使它们看起来相同,“i”在右侧的用法是其值(更具体地说,是其“r-value”),而在左侧的用法是其“l-value”。
在Java中,没有办法在数组初始化器中表达变量的“l-value”,因此您尝试的操作无效。正如其他人指出的那样,在其他语言(如C)中,可以通过使用“&”(取地址)运算符实现这一点。
由于Java有限的表达方式,通常通过对对象的“引用”来表达“存储东西的地方”的概念。然后可以使用此引用将其存储到该对象的“字段”中或调用该对象上的“方法”。
假设我们有一个像这样的类:
class MyContainer {
    String str;
    void setString(String s) { str = s; }
    String getString() { return str; }
}

我们可以将您的代码重写为以下内容:

然后我们可以重写您的代码,执行以下操作:

String[] containsValue = { "hi", "hello", "there" };

MyContainer hiCont = new MyContainer();
MyContainer helloCont = new MyContainer();
MyContainer thereCont = new MyContainer();

MyContainer[] getContainsValue = { hiCont, helloCont, thereCont };

for (int x = 0; x < getContainsValue.length; x++) {
    getContainsValue[x].setString(containsValue[x]);
}

2

Well you can use this.

Map<String,String> map = new HashMap<String,String>();
String[] str = {"hi","hello","there"};

for(int x = 0; x < str.lenght;x++){
map.put(str[x],"something you want to store");

}

1

最好的方法可能是使用Map并将其存储为键值对。

Map<String,String> myKVMap=new HashMap<String,String>();
myKVMap.put("strHi","value1");
myKVMap.put("strHello","value2");
myKVMap.put("strThere","value3");

这样你就可以消除所有变量名称和值的问题。


1

我认为你应该像使用Map一样使用Collection

Map用于以键-值对的形式存储数据。

在你的情况下,假设键是字符串,值也是字符串。

Map<String, String> mp = new Map<String, String>();

mp.put("str1","Hi");
mp.put("str2","Hello");

You can iterate over it like the below.

for(Map.Entry<String, String> ar : mp.entrySet()){

      System.out.println("Key: "+ar.getKey()+" :: "+"Value: "+ar.getValue());

 }

1

使用地图是个好主意。另一种方法是实例化类变量,然后分配值就可以了。

public void testTransfer() {
    String containsValue[] = { "hi", "hello", "there" };
    Data strHi = new Data();
    Data strHello = new Data();
    Data strThere = new Data();
    Data[] getContainsValue = { strHi, strHello, strThere };
    for (int x = 0; x < getContainsValue.length; x++) {
        getContainsValue[x].value = containsValue[x];
    }
    // print out
    System.out.println(strHi.value);
    System.out.println(strHello.value);
    System.out.println(strThere.value);
}

class Data {
    private String value;
}

0
如果我理解你的问题正确,你想通过首先在数组中查找字符串变量然后再进行赋值来实现。
我同意其他回答者的观点,如果你发现这种方法是必要的,那么它可能是不明智的。但是为了纯粹的问答精神,以下是实现方式:
interface StringAssigner {
    void assign( String strValue );
}

// ...

String strHi, strHello, strThere;

StringAssigner[] asaGetContainsValue = {
    new StringAssigner() { @Override public void assign( String strValue ) { strHi = strValue; } },
    new StringAssigner() { @Override public void assign( String strValue ) { strHello = strValue; } },
    new StringAssigner() { @Override public void assign( String strValue ) { strThere = strValue; } }
};

// ...

for (int x = 0; x < asaGetContainsValue.length; x++) {
    asaGetContainsValue[x].assign( containsValue[x] );
}

拒绝即可。


0

我同意其他答案中的观点,这似乎是为了解决某些问题而采用的一种变通方法,但如果不知道具体问题是什么,我无法提出更好的建议。

不过,回答这个问题:你可以将字符串包装在一个简单的类中,并将该类的对象引用存储在数组和strHistrHellostrThere中。这样,即使在类内部更改字符串属性,类对象本身也不会改变,因此您将看到您要寻找的行为。


或者,您可以像其他人建议的那样使用 HashMap。在您的情况下,如果您仍然想要使用 getContainsValue 数组,您可以存储键:

Map<String,String> map = new HashMap<String,String>();
map.put("strHi","");
map.put("strHello","");
map.put("strThere","");

String[] containsValue = { "hi", "hello", "there" };
String[] getContainsValue = { "strHi", "strHello", "strThere" };

for (int x = 0; x < getContainsValue.length; x++) {
    map.put(getContainsValue[x], containsValue[x]);
}

那么,map.get("strHi") 将会返回你所期望的 "hi"

1
这与String的不可变性无关。它是关于Java无法操作变量的l-values的能力。 - Stuart Marks
@StuartMarks 是的,发现得好,谢谢。我想我现在没注意到。 - lc.

0
在Java中,没有简单的方法可以实现您想要的操作。您需要的是C/C++地址运算符(&)的等效物...或者Perl使用字符串作为变量名的能力。这两者都不受Java支持。
理论上,在变量是实例变量的情况下,您可以使用反射来访问和更新它们。但是,执行此操作的代码混乱、低效且脆弱。而且它无法处理局部变量。
你最好寻找一个不同的解决方案来解决这个问题;例如使用Map,正如其他答案所建议的那样。
或者只是采用一些笨拙(但健壮且相当高效)的代码,使用switch或一系列if else if测试和原始变量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接