thenewbie
thenewbie

Reputation: 805

Storing String on array java

I want to know if is it possible to Store a String variable on a String array? I cant explain it well but here is what i do:

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

Unfortunately when i use for loop the str gets the value of st1 and st2 and st3 ans st4 not the variable it self..

This is what i want to do exactly on my mind.. Whenever a have a String array for example:

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";

Basically i want to transfer that value of containsValue[] to 3 String which is strHi, strHello, strThere that are stored in getContainsValue[]. Then use for loop to asign value to them came from containsValue[]. Is this posible? If so then can you give me some format how to do it? thanks..

Upvotes: 3

Views: 7326

Answers (10)

cl-r
cl-r

Reputation: 1264

You can use enum class as the Array needed :

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);
        }
    }
}

Output

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

See in Effective Java use of enum

Upvotes: 3

androidNoob
androidNoob

Reputation: 103

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");

}

Upvotes: 2

Stuart Marks
Stuart Marks

Reputation: 132380

The concept you are looking for is an "l-value". Briefly, when you are using a variable, are you using the value contained in the variable, or are you talking about the variable itself so that you can store something else into it? You want array that you're calling getContainsValue to have l-values for strHi, strHello, and strThere. Unfortunately there is no way to do this in Java. Initializing getContainsValue with strHi, strHello, and strThere uses the values of those variables, not their l-values.

Let's step back a bit and talk more about l-values vs values (sometimes, r-values). Consider the following code snippet:

int i = 17;
i = i + 1;

That second line is obviously not an equation; that would be nonsensical. Instead, it is an assignment. The meaning of i on the left and right sides of an assignment is different. On the right hand side, i means to use the value of that variable, in this case 17. On the left hand side, i means the variable itself, as a destination for storing values. Even though they look the same, the use of i on the right-hand side is for its value (more specifically, its r-value) and the use of i on the left-hand side is for its l-value.

In Java, there is no way to express the l-value of a variable in an array initializer, so what you're trying to do doesn't work. As others have pointed out, in other languages like C this is possible, by using the & (address-of) operator.

Since Java has limited ways of expressing l-values, usually the concept of "a place to store something into" is expressed via a reference to an object. One can then use this reference to store into fields of that object or to call methods on that object.

Suppose we have a class like this:

class MyContainer {
    String str;
    void setString(String s) { str = s; }
    String getString() { return str; }
}

We could then rewrite your code to do something like the following:

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]);
}

Upvotes: 2

lc.
lc.

Reputation: 116478

I do agree with the other answers here that this feels like a workaround for something, but without knowing what that something is I cannot suggest anything better.

To answer the question, though: you could, however, wrap the string in simple class and store the object references of that class in your array and strHi, strHello, and strThere. This way even when you change the string property inside the class, the class object itself does not change so you will see the behavior you are looking for.


Or, you can use a HashMap as others have suggested. In your case if you still want to use the getContainsValue array, you can store the keys:

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]);
}

Then, map.get("strHi") would return "hi" as you expect.

Upvotes: 0

Akshay
Akshay

Reputation: 26

Using a Map is a good idea. Another approach is to instantiate class variables, then assigning values will work.

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;
}

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

I think you should use Collection like Map.

Map is used to store data in the form of Key-Value Pairs.

Assume the Key is String and Value is a String too in your case.

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());

 }

Upvotes: 1

Judge Mental
Judge Mental

Reputation: 5239

If I am understanding your question, you want to be able to assign a regular String variable by looking it up in an array first and then making the assignment.

I agree with the other responders that if you are finding this approach necessary, it is probably ill-advised. But in the spirit of pure Q&A, here's the way:

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] );
}

Just say no.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718816

There is no simple way to do what you want to do in Java. What you would need is the equivalent of the C / C++ address-of operator (&) ... or maybe Perl's ability to use a string as a variable name. Neither of these are supported in Java.

In theory, if the variables where instance variables, you could use reflection to access and update them. But the code to do this is messy, inefficient and fragile. And it won't work with local variables.


You would be better off looking for a different solution to the problem; e.g. use a Map, as other answers have suggested.

Or just settle for some clunky (but robust and reasonably efficient) code that uses a switch or series of if else if tests and the original variables.

Upvotes: 0

kosa
kosa

Reputation: 66637

Best thing may be use Map and store as key-Value pairs.

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

This way you can eliminate all the variable name and value issues.

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

You can use 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"));

Upvotes: 10

Related Questions