being new to java after having coded only in languages such as python and javascript, the best way to describe my issue is with an example from one of those two languages. to start with the error i am getting for my java program is when i attempt to create an array directly, such as string[] narray = {{'test',1}, {'test', 2}, {'test', 3}} now doing something like this gave me an illegal initialization error so i changed it to Array[][] narray = {{'test',1}, {'test', 2}, {'test', 3}} yet it is now giving me a "cannot find symbol" error. i am at a bit of a loss as to how to create an array like this directly. in python all i would have to do is narray = [['test', 1], ['test', 2], ['test', 3]]. how would i define an array like this in java? thank you.
-
2"Java Arrays" on Google gets me thisawksp– awksp2014-06-18 02:11:58 +00:00Commented Jun 18, 2014 at 2:11
-
you forgot one more bracket, String[][] narray = {{'test',1}, {'test', 2}, {'test', 3}}Rod_Algonquin– Rod_Algonquin2014-06-18 02:12:25 +00:00Commented Jun 18, 2014 at 2:12
-
rod_algonquin that gives an incompatible types error "int and String"user3723955– user37239552014-06-18 02:14:33 +00:00Commented Jun 18, 2014 at 2:14
-
@user3723955 instead of String use Object.Rod_Algonquin– Rod_Algonquin2014-06-18 02:15:27 +00:00Commented Jun 18, 2014 at 2:15
-
aha that worked. that is exactly what i was looking for, some way to create an array with both String and intuser3723955– user37239552014-06-18 02:16:49 +00:00Commented Jun 18, 2014 at 2:16
|
Show 2 more comments
2 Answers
How about using a HashMap for your particular case :
HashMap<String,Integer> map = new HashMap<>();
map.put("foo",1);
map.put("bar",2);
map.put("baz",3);
If the values repeat themselfes then consider this pair object :
class Pair<F,S> {
public final F first;
public final S second;
public Pair(F first,S second){
this.first = first;
this.second = second;
}
}
// in your method
List<Pair<String,Integer>> myList = new ArrayList<>();
myList.add(new Parir("foo",1);
myList.add(new Parir("bar",1);
myList.add(new Parir("foo",3);
since you made the jump to a type safe language you might as well start thinking in one
Comments
Your syntax for a String[] is off for Java, I believe you wanted something like this;
String[] narray = {"test", "test", "test"};
System.out.println(Arrays.toString(narray));
// alternatively (using explicit indexes).
String[] tmp = new String[2];
tmp[0] = "1";
tmp[1] = "2";
System.out.println(Arrays.toString(tmp));
When I run the above, I get (as expected)
[test, test, test]
[1, 2]