0

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.

7
  • 2
    "Java Arrays" on Google gets me this Commented Jun 18, 2014 at 2:11
  • you forgot one more bracket, String[][] narray = {{'test',1}, {'test', 2}, {'test', 3}} Commented Jun 18, 2014 at 2:12
  • rod_algonquin that gives an incompatible types error "int and String" Commented Jun 18, 2014 at 2:14
  • @user3723955 instead of String use Object. Commented 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 int Commented Jun 18, 2014 at 2:16

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.