Java – How to Transition from JavaScript to Java

data structuresjava

I learned some javascript as my introduction into programming, and now I'm trying to move on to Java and Python and from there to c++, c#, etc.

I've been caught up with schoolwork, so I've had very little chance to learn anything yet, but I have been lurking around SO looking for easy Java questions that I might have asked myself and trying to learn from the answers.

I saw one that was kind of interesting. It was a homework assignment about finding the most efficient order of jobs to do, assuming each job took two days and had to be in sequential order. I could have easily done this in javascript, but I'm having trouble figuring out how in Java. With javascript I would just return a two dimensional array. Each element being an array containing the profit and the days to work. Ignoring whether or not that's a stupid way to return data in javascript, what is the proper way to return data like this in Java?

In other words, the javascript array I would return would look something like:

[ ['1-3-5', 50], ['2-5-8', 90], ['2-4-7', 75] ]

In Java, I would have to convert the integers to strings to start off, and then find a way to concatenate two two dimensional arrays… Needless to say, this is the wrong way to go about it.

Best Answer

Using arrays for everything is a bad idea. Even in JavaScript. But in Java even more so, because arrays are far more narrow in Java.

The elements of your return array are in fact representing results. You should communicate it accordingly:

class Result {
     public int someInt;//no idea what this actually is, but a class will allow you giving it a proper name
     public String someString;//same as with the other field. Also, I suppose String is actually wrong here, since it rather looks like a '-'-separated list of integers, which should rather be represented as an array of integers
     Result(String someString, int someInt) {
           this.someString = someString;
           this.someInt = someInt;
     }
}

And then your return value should look something like:

ArrayList.ofList(new Result('1-3-5', 50), new Result('2-5-8', 90), new Result('2-4-7', 75))
Related Topic